简体   繁体   English

如何使用C#从asp.net中的.htm页创建PDF文件

[英]How to create the PDF file from the .htm page in asp.net using C#

I have a .htm page where the design is in the page with css files. 我有一个.htm页面,其中的设计位于带有css文件的页面中。 and now i want to create this .htm page to PDF document. 现在我要创建此.htm页面为PDF文档。 So how can i do this using ASP.Net in c#. 因此,我该如何在C#中使用ASP.Net做到这一点。

You can use itext sharp. 您可以使用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. 然后,在您的Web窗体中,您需要一个包含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>

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

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