开发者

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

开发者 https://www.devze.com 2023-01-29 17:04 出处:网络
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.

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>
0

精彩评论

暂无评论...
验证码 换一张
取 消