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

隐身守侯 提交于 2020-01-03 03:04:07

问题


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#.


回答1:


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>


来源:https://stackoverflow.com/questions/4387352/how-to-create-the-pdf-file-from-the-htm-page-in-asp-net-using-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!