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 asp.net 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 : http://sourceforge.net/projects/itextsharp/
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.ClearContent();       
                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. 
                myDiv.RenderControl(htextw);      
                Document document = new Document();       
                PdfWriter.GetInstance(document, Response.OutputStream);   
                document.Open();         
                StringReader str = new StringReader(stw.ToString()); 
                HTMLWorker htmlworker = new HTMLWorker(document);  
               htmlworker.Parse(str);       
               document.Close();        
               Response.Write(document);  
               Response.End();   
         }
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 asp.net forms:

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

Hope this helps.


Regards,
Mostafa Arafa
twitter.com/mostafaelzoghbi