3
votes

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.

2
USe Full Path For your Images then Its working. - Manish Sharma
When i give full path also its not Working... It take Image path as localhost:58095/testProject/D:/testProject/Images/image1.png and that image not displaying in the page.. and it generates pdf for text contents. - Gopalakrishnan
Do you know how to get this working to actually render the page as a pdf and look the same as it would on the web page itself? - Eric Garrison

2 Answers

1
votes

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.

0
votes

Use

http://localhost:58095/Images/image1.png 

to get image path. Hope it will help you. localhost:58095 is Your local machine address.