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: 

  1. using iTextSharp.text;  
  2. using iTextSharp.text.pdf;  
  3. using iTextSharp.text.html;  
  4. using iTextSharp.text.html.simpleparser;  
  5. using System.Drawing; 
Design a page.

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

 

  1. protected void Button1_Click(object sender, EventArgs e)  
  2. {  
  3.     string attachment = "attachment; filename=" + "abc" + ".pdf";  
  4.     Response.ClearContent();  
  5.     Response.AddHeader("content-disposition", attachment);  
  6.     Response.ContentType = "application/pdf";  
  7.     StringWriter s_tw = new StringWriter();  
  8.     HtmlTextWriter h_textw = new HtmlTextWriter(s_tw);  
  9.     h_textw.AddStyleAttribute("font-size""7pt");  
  10.     h_textw.AddStyleAttribute("color""Black");  
  11.     Panel1.RenderControl(h_textw);//Name of the Panel  
  12.     Document doc = new Document();  
  13.     doc = new Document(PageSize.A4, 5, 5, 15, 5);  
  14.     FontFactory.GetFont("Verdana", 80, iTextSharp.text.Color.RED);  
  15.     PdfWriter.GetInstance(doc, Response.OutputStream);  
  16.     doc.Open();  
  17.     StringReader s_tr = new StringReader(s_tw.ToString());  
  18.     HTMLWorker html_worker = new HTMLWorker(doc);  
  19.     html_worker.Parse(s_tr);  
  20.     doc.Close();  
  21.     Response.Write(doc);  
  22. }  
  23. public override void VerifyRenderingInServerForm(Control control)  
  24. {  
  25. } 

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.