Gopalakrishnan
Gopalakrishnan

Reputation: 517

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.

Upvotes: 3

Views: 12397

Answers (2)

user4600813
user4600813

Reputation: 1

Use

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

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

Upvotes: 0

Mayank Pathak
Mayank Pathak

Reputation: 3681

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.

Upvotes: 1

Related Questions