Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate PDF from a HTML page with images using iTextSharp

I used iTextSharp.dll to create pdf. But that works only for text HTML content. If I use images on my page it throws an exception that images are not found.

my Design file

<asp:Panel ID="pdfPannel" runat="server">
 
      Sample Text
<img src="../Images/image1.png"/>


</asp:Panel>

<asp:Button ID="btnSave" runat="server" Text="Save As PDF" onclick="btnSave_Click" />

my method:

protected void btnSave_Click(object sender, EventArgs e)
{

Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=print.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
pdfPannel.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();

}

when I click that save button I'm getting the following error

Could not find a part of the path 'C:\Program Files\Common Files\Microsoft Shared\DevServer\Images\image1.png'.

Please tell me is there any alternate solution to create pdf.

like image 319
Gopalakrishnan Avatar asked Nov 30 '25 21:11

Gopalakrishnan


1 Answers

Your code looks fine. Problem seems with the image's path. Try setting it to fully qualified path to images and it will work for you.

Also if you are manipulating HTML from the server side code. Then I'll suggest you to map image paths using Server.MapPath(). and it will work fine.

like image 76
Mayank Pathak Avatar answered Dec 02 '25 09:12

Mayank Pathak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!