1

I am using itextsharp dll to print web page in PDF . I have a <img src="Images/flower.jpg" /> in my html file. The button click event below will render PDF fine when I don't have the image. With the image, I got this error:

Could not find a part of the path 'C:\Program Files (x86)\Common Files\Microsoft Shared\DevServer\10.0\Images\flower.jpg'

Here is my code:

    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=TestPage.pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        this.Page.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();
    }
4
  • I have a <img src="Images/flower.jpg" /> Commented Oct 23, 2013 at 21:11
  • In your HTML you need to give an absolute path to the image since a relative path would mean relative to the current working directory which is the path which you see when the error pops up. Commented Oct 23, 2013 at 21:12
  • That works. Thanks. This would mean I have to update the path once it moves to production server. Commented Oct 23, 2013 at 21:18
  • Yes, see my answer for a potentially better alternative if you have access to the image url through code. Don't forget to upvote and accept :) Commented Oct 23, 2013 at 21:20

1 Answer 1

2

The easiest solution should be to change:

<img src="Images/flower.jpg" />

to:

<img src="http://www.yourwebsite.com/Images/flower.jpg" />

Otherwise you can use Server.MapPath("Images/flower.jpg") to get the full URL by code. However that implies you having to know the relative path to the image (meaning access to the raw html) at compile-time, which makes your code less maintainable.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.