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

时间:2021-03-22 00:26:43

I used iTextSharp.dll to create pdf. but that works only for text HTML content. if i use images in my page it throughs exception that images are not found...

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

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 im getting 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。

Thanks in Advance..

提前致谢..

2 个解决方案

#1


1  

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.

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

#2


0  

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是您的本地计算机地址。

#1


1  

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.

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

#2


0  

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是您的本地计算机地址。