Create Multi-Page PDF Using iTextSharp And jQuery In ASP.NET

Introduction

This article explains how we can create a multi-page pdf using Ajax and HttpHandler using iTextSharp. A few days back, I had gone through the requirement where I had to create a user resume using iTextsharp. Hence, I will explain how to create multi-page pdf; i.e., according to the data of a user the pdf page will increase automatically. Before we start, we should know what is iTestsharp, chunk, phrase, paragraph and document; which are provided by Itextsharp.
 
What is iTextSharp?

iTextsharp is a PDF library which helps us to create and maintain our document in the portable document format (PDF). To use ItextSharp, you need to add the reference of itextsharp dll.
 
Chunk

Chunk is the smallest text. If we want to show some text over the pdf, we can use Chunk. We can bind the data on the chunk; either static or dynamic from the database.
 
Example
 
Chunk chunk = new Chunk("Education:"); Here I bind Static Education field on the Chunk.
Chunk chunk1 = new Chunk(["Degree"].ToString()); here I bind user degree dynamically from the database.
 
Hence, chunk is nothing but  <asp:label>, which is used to show text.
 
Phrase

Phrase is the collection of chunks or we can say phrase is the container where we can add multiple chunks and show on pdf.
Example, 
  1. Phrase pExample = new Phrase();  
  2. pExample.Add(chunk);  
  3. pExample.Add(new Chunk(Environment.NewLine));  
  4. pExample.Add(chunk1);  
You can see above that I created one phrase “pExample” and added multiple chunks on that phrase. If we want a one line space between two chunks, we use Environment.NewLine.
 
Paragraph
 
Now, paragraph is the most important feature provided by iTextSharp, which holds the sequence of chunks and phrases.
  1. Paragraph para = new Paragraph();  
  2. para.Add(pExample);  
Document

Document is the sequence of the collection of chunks, phrases and paragraphs. We write the document on Pdf and data is shown accordingly.
  1. Document doc = new Document();  
  2. doc.Add(para);  
This article consists of three main steps, 
  1. Add the reference of itextsharp.
  2. Using jQuery call to the Handler to creating the pdf.
  3. Set Fonts, style of pdf text using iTestsharp. 
1. Add the reference of itextsharp
 
If we want to use the feature of iTextSharp, we have to add the reference. Hence, I explain how we can achieve that.

Step 1
 
Right click the reference and select add reference option, shown in the image below:
 
 
Step 2

Once you click the add reference option, select the dll from the location, where you saved the dll.
 
 
 
Step 3

When you successfully add the iTextSharp reference, you can use the namespace which is required to create the pdf. 
  1. using iTextSharp.text;  
  2. using iTextSharp.text.pdf;  
  3. using iTextSharp.text.pdf.draw;  
2. Using jQuery call to the handler for creating the pdf.
 
When you are done with iTextSharp dll reference, create the HTML page and on the Click event of the button, call the handler. I explain these points in different steps.
 
Step 1

Create your HTML with the input type button and assign it a useful ID, because on the click of that button, we call the specific method in handler page.
  1. <html>  
  2.   
  3. <head>  
  4.   
  5.     <body>  
  6.         <div>  
  7.             <div>  
  8.                 <input type="submit" id="btnDownloadResume" value="Download">  
  9.             </div>  
  10.         </div>  
  11.     </body>  
  12.     <script type="text/javascript">  
  13.         $("#btnDownloadResume").click(function()  
  14.         {  
  15.             window.location.href = "handlername?method=getpdf";  
  16.         })  
  17.     </script>  
  18. </head>  
  19.   
  20. </html>  
Step 2
  1. public void ProcessRequest(HttpContext context)  
  2. {  
  3.     try  
  4.     {  
  5.         switch (context.Request.QueryString["method"].ToLower())  
  6.         {  
  7.             case "getpdf":  
  8.                 GetPdf(context);  
  9.                 break;  
  10.         }  
  11.     }  
  12. }  
  13. private void GetPdf(HttpContext context)  
  14. {  
  15.     Paragraph para = new Paragraph();  
  16.     var pagesize = new iTextSharp.text.Rectangle(iTextSharp.text.PageSize.A4);  
  17.     //Set Background color of pdf    
  18.     pagesize.BackgroundColor = iTextSharp.text.Color.WHITE;  
  19.     var left_margin = 25;  
  20.     var top_margin = 25;  
  21.     var bottom_margin = 25;  
  22.     string filePath = HttpContext.Current.Server.MapPath("~/resume/");  
  23.     var pathForDownLoad = "~/resume/" + userId + "/" + "resume.pdf";  
  24.     if (File.Exists(filePath + "/" + "resume.pdf"))  
  25.     {  
  26.         File.Delete((filePath + "/" + "resume.pdf"));  
  27.     }  
  28.     if (!Directory.Exists(filePath))  
  29.     {  
  30.         Directory.CreateDirectory(filePath);  
  31.     }  
  32.     string newFilePath = filePath + "/" + "resume.pdf";  
  33.     try  
  34.     {  
  35.         // create a iTextSharp.text.Document object:    
  36.         iTextSharp.text.Document doc = new iTextSharp.text.Document(pagesize, left_margin, 10, top_margin, bottom_margin);  
  37.         PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(newFilePath, FileMode.Create));  
  38.         DataSet objDataSet = // your database call from where you get the user Record and store into dataset.    
  39.             iTextSharp.text.Font mainFont = new iTextSharp.text.Font();  
  40.         iTextSharp.text.Font boldFont = new iTextSharp.text.Font();  
  41.         mainFont = FontFactory.GetFont("Arial", 10, iTextSharp.text.Font.NORMAL, new iTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml("#000000")));  
  42.         boldFont = FontFactory.GetFont("Arial", 12, iTextSharp.text.Font.BOLD);  
  43.         if (objDataSet.Tables.Count > 0)  
  44.         {  
  45.             doc.Open();  
  46.             Phrase phrase_personal = new phrase_personal();  
  47.             Chunk chunk1 = new Chunk(objDataSet.Tables[0].Rows[0]["Name"].ToString(), boldFont);  
  48.             phrase_personal.Add(chunk1);  
  49.             phrase_personal.Add(new Chunk(Environment.NewLine));  
  50.             Chunk chunk2 = new Chunk(objDataSet.Tables[0].Rows[0]["Country"].ToString() + ", " + objDataSet.Tables[0].Rows[0]["State"].ToString() + ", " + objDataSet.Tables[0].Rows[0]["City"].ToString() + ", " + objDataSet.Tables[0].Rows[0]["Zip"].ToString(), mainFont);  
  51.             phrase_personal.Add(chunk2);  
  52.             Chunk chunk3 = new Chunk(objDataSet.Tables[0].Rows[0]["Phone"].ToString(), mainFont);  
  53.             phrase_personal.Add(chunk3);  
  54.             Chunk chunk4 = new Chunk(objDataSet.Tables[0].Rows[0]["Email"].ToString(), mainFont);  
  55.             phrase_personal.Add(chunk4);  
  56.             para.Add(phrase_personal);  
  57.             Phrase Phrase_Title = new Phrase();  
  58.             Phrase_Title.Add(new Chunk(Environment.NewLine));  
  59.             Chunk chunk5 = new Chunk("SUMMARY OF QUALIFICATIONS:", boldFont);  
  60.             Phrase_Title.Add(chunk5);  
  61.             Phrase_Title.Add(new Chunk(Environment.NewLine));  
  62.             if (objDataSet.Tables[4].Rows.Count > 0)  
  63.             {  
  64.                 Chunk chunk6 = new Chunk(objDataSet.Tables[4].Rows[0]["Description"].ToString(), mainFont);  
  65.                 Phrase_Title.Add(chunk6);  
  66.                 Phrase_Title.Add(new Chunk(Environment.NewLine));  
  67.                 para.Add(Phrase_Title);  
  68.             }  
  69.             Phrase phrase_edu = new Phrase();  
  70.             Chunk chunk7 = new Chunk("EDUCATION:", boldFont);  
  71.             phrase_edu.Add(chunk7);  
  72.             phrase_edu.Add(new Chunk(Environment.NewLine));  
  73.             if (objDataSet.Tables[1].Rows.Count > 0)  
  74.             {  
  75.                 foreach(DataRow dr in objDataSet.Tables[1].Rows)  
  76.                 {  
  77.                     Chunk chunk8 = new Chunk(dr["Degree"].ToString() + " From " + dr["College"].ToString() + " in " + dr["PassoutYear"].ToString(), mainFont);  
  78.                     phrase_edu.Add(chunk8);  
  79.                     phrase_edu.Add(new Chunk(Environment.NewLine));  
  80.                 }  
  81.             }  
  82.             para.Add(phrase_edu);  
  83.             phrase_edu.Add(new Chunk(Environment.NewLine));  
  84.             Phrase phrase3 = new Phrase();  
  85.             Chunk chunk9 = new Chunk("PROFESSIONAL EXPERIENCE:", boldFont);  
  86.             phrase3.Add(new Chunk(Environment.NewLine));  
  87.             phrase3.Add(chunk9);  
  88.             phrase3.Add(new Chunk(Environment.NewLine));  
  89.             para.Add(phrase3);  
  90.             if (objDataSet.Tables[2].Rows.Count > 0)  
  91.             {  
  92.                 foreach(DataRow dr in objDataSet.Tables[2].Rows)  
  93.                 {  
  94.                     Phrase phrase_Exp = new Phrase();  
  95.                     Chunk chunk10 = new Chunk("Project Name: " + dr["ProjectName"].ToString(), boldFont);  
  96.                     phrase_Exp.Add(new Chunk(Environment.NewLine));  
  97.                     phrase_Exp.Add(chunk10);  
  98.                     phrase_Exp.Add(new Chunk(Environment.NewLine));  
  99.                     Chunk chunk11 = new Chunk(dr["StartDate"].ToString() + "-" + dr["EndDate"].ToString(), mainFont);  
  100.                     phrase_Exp.Add(chunk11);  
  101.                     phrase_Exp.Add(new Chunk(Environment.NewLine));  
  102.                     Chunk chunk12 = new Chunk(dr["EmployerName"].ToString() + ", " + dr["ExpCity"].ToString() + ", " + dr["ExpState"].ToString() + ", " + dr["ExpCounrty"], mainFont);  
  103.                     phrase_Exp.Add(chunk12);  
  104.                     phrase_Exp.Add(new Chunk(Environment.NewLine));  
  105.                     Chunk chunk13 = new Chunk(dr["PositionTitle"].ToString() + ", " + dr["ProjectRole"].ToString(), mainFont);  
  106.                     phrase_Exp.Add(chunk13);  
  107.                     Chunk chunk14 = new Chunk(dr["ProjectDescription"].ToString(), mainFont);  
  108.                     phrase_Exp.Add(chunk14);  
  109.                     Chunk chunk15 = new Chunk("Responsibilities:", mainFont);  
  110.                     phrase_Exp.Add(chunk15);  
  111.                     Chunk chunk16 = new Chunk(dr["Responsibility"].ToString(), mainFont);  
  112.                     phrase_Exp.Add(chunk16);  
  113.                     Chunk chunk17 = new Chunk("Environment: " + dr["TechnologyUsed"].ToString(), mainFont);  
  114.                     phrase_Exp.Add(chunk17);  
  115.                     Chunk chunk18 = new Chunk("Team Size:" + dr["TeamSize"].ToString(), mainFont);  
  116.                     phrase_Exp.Add(chunk18);  
  117.                     para.Add(phrase_Exp);  
  118.                 }  
  119.             }  
  120.             doc.Add(para);  
  121.             doc.Close();  
  122.         }  
  123.     }  
  124.     catch (Exception ex)  
  125.     {}  
  126. }  
3. Set Font style of pdf text using iTextSharp.
 
Once you complete with the code and write text on Pdf, the main remaining work is to set font color, font size, and font style in the pdf. Hence, I will explain how to set the font size and color of the pdf.
 
In the above code you have seen, 
  1. iTextSharp.text.Font boldFont = new iTextSharp.text.Font();  
  2. boldFont = FontFactory.GetFont("Arial", 12, iTextSharp.text.Font.BOLD);  
Using iTextSharp.text.Font class, we can set the font style, font color, font size into the variable and apply that variable to the chunks.
 
Example 
  1. Chunk(objDataSet.Tables[0].Rows[0]["Name"].ToString(), boldFont);  
Here, I applied bold font to the name chunk. When the output will display, the name will appear bold and the size is 12 along with Arial font.
 
Similarly, you can create other variables, set its font and apply this variable in the different chunks.
 
Output
 
Page 1
 


Page 2
 
 
Finally, we created a resume and the number of pages will increase, according to the data.
 
Summary
 
Today, we have discussed what is iTextSharp and its different properties. We also discussed what are the chunks, phrase, paragraph , document and how they are related to each other. We created a multi-page pdf using iTextSharp.


Similar Articles