Thursday, June 02, 2011

Export ASP.NET Form to PDF

Hi All,
I was trying to export the content of an ASP.NET page in my project to PDF, and after i spent few hours to figure out how to achieve this using standard Resposnse.Output() with pdf format, I ended up having different errors & bugs without successfully export a simple html page to pdf.

Having complex page with complex controls, you need simply to install iTextSharp PDF tool, easy and free tool to export your page to pdf.

Here is the steps:
1) Install iTextSharp tool :
2) Add itextsharp.dll in your project.
3) Create your function to export to PDF as follows:

        protected void ExportToPDF()  
                // Start exporting page content
                string attachment = "attachment; filename=MostafaElzoghbi.pdf"; 
                Response.AddHeader("content-disposition", attachment); 
                Response.ContentType = "application/pdf";    
                StringWriter stw = new StringWriter();   
                HtmlTextWriter htextw = new HtmlTextWriter(stw); 
                // We want to render the whole page, you can change this with the control name or portion you want to export. 
                Document document = new Document();       
                PdfWriter.GetInstance(document, Response.OutputStream);   
                StringReader str = new StringReader(stw.ToString()); 
                HTMLWorker htmlworker = new HTMLWorker(document);  
If you get this error: A control has to be placed inside a form tag with runat=server attribute.

Just add this function in your code to override the pre render validation step in forms:

public override void VerifyRenderingInServerForm(Control control)
 { /* Do nothing */ }

Hope this helps.

Mostafa Arafa

No comments: