简体   繁体   English

使用 iTextSharp 从带有图像的 HTML 页面生成 PDF

[英]Generate PDF from a HTML page with images using iTextSharp

I used iTextSharp.dll to create pdf.我使用 iTextSharp.dll 创建 pdf。 But that works only for text HTML content.但这仅适用于文本 HTML 内容。 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'.找不到路径“C:\\Program Files\\Common Files\\Microsoft Shared\\DevServer\\Images\\image1.png”的一部分。

Please tell me is there any alternate solution to create pdf.请告诉我是否有任何替代解决方案来创建 pdf。

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.此外,如果您正在从服务器端代码操作HTML Then I'll suggest you to map image paths using Server.MapPath() .然后我建议你使用Server.MapPath()映射图像路径。 and it will work fine.它会正常工作。

Use采用

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

to get image path.获取图像路径。 Hope it will help you.希望它会帮助你。 localhost:58095 is Your local machine address. localhost:58095是您的本地机器地址。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM