Blog

Export HTML To PDF

By Dhanraj Patil Feb 14 2013
Exporting HTML To PDF using ItextSharp DLL.
    • Like
    • Love It
    • Awesome
    • Interesting
    • It's Okay
    • Thumbs Down
  • 2.5k
  • 0
There would be some task where we need to Get PDF Format Document from html.

Following code is written under the button_click Event. 

protected void btnExportPDF_Click(object sender, EventArgs e)
{
    Response.ContentType = "application/pdf";
    Response.AddHeader("content-disposition", "attachment;filename=Investment_Declaration_Form.pdf");
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    StringWriter sw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);

    this.divToPdf.RenderControl(hw);
    //where divToPdf is the ContentPlaceHolder Id in which whole html contains.

    StringReader sr = new StringReader(sw.ToString());
    Document pdfDoc = new Document(PageSize.A4, 10, 10, 2, 10);
    HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
    PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
    pdfDoc.Open();
    htmlparser.Parse(sr);
    pdfDoc.Close();
    Response.Write(pdfDoc);
    Response.End();
}