Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Images don't display in PDF

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.

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;
}

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

How can I solve this?

like image 359
HerrimanCoder Avatar asked Dec 15 '22 01:12

HerrimanCoder


1 Answers

Use the absolute path to the images.

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

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

like image 130
Ibu Avatar answered Dec 29 '22 06:12

Ibu