1

我正在开发 MVC 应用程序,但我遇到了 XMLWorker 和 ImageProvider 的问题。我的图像没有显示在它收到的 pdf 中渲染 html。

这是代码:

        var bytes = Encoding.UTF8.GetBytes(html);
        string cssPath = HttpContext.Current.Server.MapPath("~/Content");

        using (MemoryStream input = new MemoryStream(bytes))
        {
            MemoryStream output = new MemoryStream();
            using (Document pdfDoc = new Document(PageSize.LETTER, 50, 50, 50, 50))
            {
                using (PdfWriter pdfWrt = PdfWriter.GetInstance(pdfDoc, output))
                {
                    pdfWrt.CloseStream = false;
                    pdfWrt.PageEvent = new PdfWriterEvents("watermark");
                    pdfDoc.Open();
                    HtmlPipelineContext context = new HtmlPipelineContext(null);
                    context.SetTagFactory(iTextSharp.tool.xml.html.Tags.GetHtmlTagProcessorFactory());
                    context.SetImageProvider(new MyImageProvider());
                    var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true);
                    cssResolver.AddCssFile(cssPath + "\\main.css", true);
                    IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(context, new PdfWriterPipeline(pdfDoc, pdfWrt)));
                    var worker = new XMLWorker(pipeline, true);
                    var parser = new XMLParser();
                    parser.AddListener(worker);


                    using (TextReader sr = new StringReader(html))
                    {
                        parser.Parse(sr);
                    }
                    pdfDoc.Close();
                    byte[] test = output.GetBuffer();
                    File.WriteAllBytes(HttpContext.Current.Server.MapPath("~/Content/PDFs/test.pdf"), test);

                }
            }
        }

这是我的 ImageProvider 实现:

public class MyImageProvider : AbstractImageProvider
{
    public override string GetImageRootPath()
    {
        return HttpContext.Current.Server.MapPath("~/Content/Images");
    }
} 

任何想法?

4

1 回答 1

0

我必须更改图像源标签以包含整个 url 才能让它们工作。

于 2015-12-30T22:50:44.550 回答