Getting Started ITextSharp in ASP.Net

This article explains how to use iTextSharp and its features in ASP.Net.

What is ITextSharp?  iTextSharp is a free and open source assembly that helps to convert page output or HTML content in a PDF file.

You can download it from here:

http://sourceforge.net/projects/itextsharp/

Now add that DLL in the application.

Getting Started: Start Visual Studio and create a new website in ASP.Net and add these 2 DLLs to the solution.

  • Itextsharp.dll
  • itextsharp.pdfa.dll

Now let's work on the UI part.

  1. <div id="print" runat="server">  
  2.     <h1>About Raj Kumar</h1>  
  3.          <div>  
  4.               <table>  
  5.                   <tr>  
  6.                       <td>  
  7.                           <img src="http://www.c-sharpcorner.com/UploadFile/AuthorImage/raj1979.jpg" height="100" width="120" />  
  8.                       </td>  
  9.                       <td></td>  
  10.                  </tr>  
  11.                  <tr>  
  12.                      <td>Name: </td>  
  13.                      <td>Raj Kumar</td>  
  14.                  </tr>  
  15.                  <tr>  
  16.                       <td>Designation: </td>  
  17.                      <td>Asst. Project Manager</td>  
  18.                  </tr>  
  19.                  <tr>  
  20.                       <td>Work Experience: </td>  
  21.                       <td>9 Years in IT</td>  
  22.                  </tr>  
  23.                  <tr>  
  24.                       <td>About: </td>  
  25.                      <td>Raj Kumar is two times Microsoft MVP(Client App Dev) and four times C# Corner MVP,  working as asst project manager with many hands on experience using ASP.NET 2.0/3.5, AJAX, MVC, C#, Visual Basic .NET, SQL Server 2005/2008, Oracle, WPF, WCF, XAML, HTML5, jQuery, Windows Phone, Web Api, LightSwitch 2012 and Silverlight. He has over 9 years of IT experience working most on Microsoft technologies. He holds Master's degree in Computer Science. When he is not writing code, he likes to write articles and play cricket. You can read my blogs here http://www.dotnetbloggers.com OR Reach him at [email protected] </td>  
  26.                  </tr>  
  27.                  <tr>  
  28.                      <td>Location: </td>  
  29.                     <td>New Delhi INDIA</td>  
  30.                  </tr>  
  31.              </table>  
  32.         </div>  
  33.     </div>  
  34.     <div>  
  35.         <asp:Button ID="btnCreatePDF" runat="server" Text="Create PDF" OnClick="btnCreatePDF_Click" />  
  36.     </div>   

As you can see there is a div "<div id="print" runat="server"> " and a table inside of that div, so I need to export this content to a PDF file on button click.

Let's add these namespaces first in code behind.

  1. using iTextSharp.text;  
  2. using iTextSharp.text.pdf;  
  3. using iTextSharp.text.html;  
  4. using System.IO;  
  5. using System.Text.RegularExpressions;  
  6. using iTextSharp.text.html.simpleparser;

And write this code for the button click event.

  1. protected void btnCreatePDF_Click(object sender, EventArgs e)  
  2. {  
  3.     Response.ContentType = "application/pdf";  
  4.     Response.AddHeader("content-disposition""attachment;filename=FileName.pdf");  
  5.     Response.Cache.SetCacheability(HttpCacheability.NoCache);  
  6.     StringWriter sw = new StringWriter();  
  7.     HtmlTextWriter w = new HtmlTextWriter(sw);  
  8.     print.RenderControl(w);  
  9.     string htmWrite = sw.GetStringBuilder().ToString();  
  10.     htmWrite = Regex.Replace(htmWrite, "</?(a|A).*?>""");  
  11.     htmWrite = htmWrite.Replace("\r\n""");  
  12.     StringReader reader = new StringReader(htmWrite);  
  13.     Document doc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);  
  14.     string pdfFilePath = Server.MapPath(".") + "/PDFFiles";  
  15.     HTMLWorker htmlparser = new HTMLWorker(doc);  
  16.     PdfWriter.GetInstance(doc, Response.OutputStream);  
  17.     doc.Open();  
  18.     try  
  19.     {  
  20.         htmlparser.Parse(reader);  
  21.         doc.Close();  
  22.         Response.Write(doc);  
  23.         Response.End();  
  24.     }  
  25.     catch (Exception ex)  
  26.     { }  
  27.     finally  
  28.     {  
  29.        doc.Close();  
  30.     }  
  31. } 

To stop this error "RegisterForEventValidation can only be called during Render();", you need to write this method.

  1. public override void VerifyRenderingInServerForm(Control control)  
  2. {  
  3.     /* Verifies that the control is rendered */  
  4. } 

Hit F5 to see the output.

img1.jpg

 Image 1.

Now click on the button.

img2.jpg

Image 2.

When the button is clicked there is one PDF file opened like this, as you will see all the details have been exported to the PDF file. For more information download the attached sample.


Similar Articles