使用ASP.NET -C从HTML页面生成PDF文档

时间:2013-08-01 07:23:03

标签: c# asp.net pdf pdf-generation itextsharp

我使用iTextSharp.dll创建pdf。但这仅适用于文本HTML内容。如果我在我的页面中使用图像,则通过例外找不到图像...

我的设计文件

<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" />

我的方法:

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();

}

当我点击保存按钮时出现错误

  

无法找到路径'C:\ Program Files \ Common的一部分   Files \ Microsoft Shared \ DevServer \ Images \ image1.png'。

请告诉我是否有任何替代解决方案来创建pdf。

先谢谢..

2 个答案:

答案 0 :(得分:1)

您的代码看起来很好。问题似乎与图像的路径有关。尝试将其设置为完全限定路径到图像,它将适合您。

此外,如果您正在从服务器端代码操作HTML。然后我建议你使用Server.MapPath()映射图像路径。它会正常工作。

答案 1 :(得分:0)

使用

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

获取图像路径。希望它会对你有所帮助。 localhost:58095是您的本地计算机地址。

相关问题