图片不以PDF显示

图片不以PDF显示

问题描述:

我有一个通过asp.net呈现的相当简单的HTML页面.通过 HtmlRenderer.PdfSharp 运行后,PDF中的图片看起来很漂亮,只是没有出现图像.即使网页本身确实正确显示了图像,也只是PDF中缺少图像的红色X.

I have a fairly simple HTML page rendered via asp.net. It looks beautiful in the PDF after running it through HtmlRenderer.PdfSharp EXCEPT that the images don't appear. Just the red X of a missing image in the PDF even though the web page itself does display the image correctly.

这是我的HtmlRenderer.PdfSharp代码:

Here is my HtmlRenderer.PdfSharp code:

public void BuildPDF( string url, string pdfPath ) {
   string html = GetHTML(url);
   Byte[] res = null;
   using( MemoryStream ms = new MemoryStream() ) {
      using( FileStream file = new FileStream(pdfPath, FileMode.Create, FileAccess.Write) ) {
         byte[] bytes = new byte[ms.Length];
         var pdf = TheArtOfDev.HtmlRenderer.PdfSharp.PdfGenerator.GeneratePdf(html, PdfSharp.PageSize.A4);
         pdf.Save(ms);
         res = ms.ToArray();
         file.Write(res, 0, res.Length);
         ms.Close();
      }
   }
}

private string GetHTML(string url) {
   string html = string.Empty;
   HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
   request.AutomaticDecompression = DecompressionMethods.GZip;

   using( HttpWebResponse response = (HttpWebResponse)request.GetResponse() )
   using( Stream stream = response.GetResponseStream() )
   using( StreamReader reader = new StreamReader(stream) ) {
      html = reader.ReadToEnd();
   }

   return html;
}

这是未在PDF中呈现的img HTML:<img src="images/ChartImg.png" />

And here is the img HTML that doesn't render in the PDF: <img src="images/ChartImg.png" />

我该如何解决?

使用图像的绝对路径.

Use the absolute path to the images.

<img src="http://example.org/images/ChartImg.png" />

您可以解析html并先将其替换为字符串,然后再将其传递给pdf转换器.

You can parse the html and do a string replace first before passing it to the pdf converter.