Export HTML To PDF

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();
}
X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now