Convert Aspx Page Into PDF in ASP.NET

Introduction

This article explains how to export an aspx page to a PDF file.

Requirement

The only requirement is to add the DLL of "ITextSharp" to the application.

Code

In the code behind add the following namespaces:

using iTextSharp.text;

using iTextSharp.text.pdf;
using
iTextSharp.text.html;
using
iTextSharp.text.html.simpleparser;
using
System.Drawing;

Design a page.

Place the following code on the button click event to convert the aspx page into PDF:

protected void Button1_Click(object sender, EventArgs e)

{
       
string attachment = "attachment; filename=" + "abc" + ".pdf";
        Response.ClearContent();

        Response.AddHeader(
"content-disposition", attachment);
        Response.ContentType =
"application/pdf";
       
StringWriter s_tw = new StringWriter();
       
HtmlTextWriter h_textw = new HtmlTextWriter(s_tw);
        h_textw.AddStyleAttribute(
"font-size", "7pt");
        h_textw.AddStyleAttribute(
"color", "Black");
        Panel1.RenderControl(h_textw);
//Name of the Panel
       
Document doc = new Document();
        doc =
new Document(PageSize.A4, 5, 5, 15, 5);
       
FontFactory.GetFont("Verdana", 80, iTextSharp.text.Color.RED);
       
PdfWriter.GetInstance(doc, Response.OutputStream);
        doc.Open();

       
StringReader s_tr = new StringReader(s_tw.ToString());
       
HTMLWorker html_worker = new HTMLWorker(doc);
        html_worker.Parse(s_tr);

        doc.Close();
        Response.Write(doc);

   }

public override void VerifyRenderingInServerForm(Control control)

{
}

Save all and run; an error will occur as in the following image:

asp-net.jpg

This error occurs when we render a control into a response. Use the following point to resolve this error:

Add  EnableEventValidation="false" in the page directive on the source of your page at the top.

Now save all and view the page in the browser; when you click on the button to convert the apx page into a PDF it will work.

Up Next
    Ebook Download
    View all
    Learn
    View all