如何使用 C# 从 asp.net 中的 .htm 页面创建 PDF 文件 [英] How to create the PDF file from the .htm page in asp.net using C#
本文介绍了如何使用 C# 从 asp.net 中的 .htm 页面创建 PDF 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 .htm 页面,其中设计位于带有 css 文件的页面中.现在我想将此 .htm 页面创建为 PDF 文档.那么我如何在 c# 中使用 ASP.Net 来做到这一点.
解决方案
您可以使用 itext 锐化.
导入这些
使用 iTextSharp.text.html.simpleparser;使用 iTextSharp.text.pdf;使用 iTextSharp.text;
接下来是添加这个方法
public void ConvertHtmlStringToPDF(){StringBuilder sb = new StringBuilder();StringWriter tw = new StringWriter(sb);HtmlTextWriter hw = new HtmlTextWriter(tw);///这是来自webform的面板pnlPDF.RenderControl(hw);字符串 htmlDisplayText = sb.ToString();文档文档 = 新文档();MemoryStream ms = new MemoryStream();PdfWriter writer = PdfWriter.GetInstance(document, ms);StringReader se = new StringReader(htmlDisplayText);HTMLWorker obj = new HTMLWorker(document);文档.Open();obj.Parse(se);//第 5 步:我们关闭文档文档.关闭();Response.Clear();Response.AddHeader("content-disposition", "attachment; filename=report.pdf");Response.ContentType = "申请/pdf";Response.Buffer = true;Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);Response.OutputStream.Flush();Response.End();}
然后在您的网络表单中,您需要有一个包含 html 的面板.这样做的目的是让你能够在服务器端调用它.
<div>html内容
</asp:面板>
I have a .htm page where the design is in the page with css files. and now i want to create this .htm page to PDF document. So how can i do this using ASP.Net in c#.
解决方案
You can use itext sharp.
import these
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
using iTextSharp.text;
Next is add this method
public void ConvertHtmlStringToPDF()
{
StringBuilder sb = new StringBuilder();
StringWriter tw = new StringWriter(sb);
HtmlTextWriter hw = new HtmlTextWriter(tw);
///This is the panel from the webform
pnlPDF.RenderControl(hw);
string htmlDisplayText = sb.ToString();
Document document = new Document();
MemoryStream ms = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(document, ms);
StringReader se = new StringReader(htmlDisplayText);
HTMLWorker obj = new HTMLWorker(document);
document.Open();
obj.Parse(se);
// step 5: we close the document
document.Close();
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=report.pdf");
Response.ContentType = "application/pdf";
Response.Buffer = true;
Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
Response.OutputStream.Flush();
Response.End();
}
Then in your webform you need to have a panel which contains the html. The purpose of this is for you to be able to call it on the server side.
<asp:Panel ID="pnlPDF" runat="server">
<div>
html contents
</div>
</asp:Panel>
这篇关于如何使用 C# 从 asp.net 中的 .htm 页面创建 PDF 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文