Datatable To PDF In C#

In this article, I have explained how to convert a DataTable into PDF using C# and iTextSharp.

You can convert any C# DataTable into PDF using iTextSharp with C#, and download the PDF file. Let's see how.
 
Step 1 - Install the iTextSharp package into your existing project
  • Open the Package Manager console from Tools--> NuGet Package Manager ->Package Manager console. 
  • Write the following command and press Enter.
Install-Package iTextSharp 
  • You can install with a particular version as well. For more information about this package, please visit here.
Step 2 - Create a button into your View page.
  1. <button onclick="ExportToPDF();" class="btn btn-primary" value="PDF"><i class="k-icon k-i-file-pdf" style="color:white;"></i> PDF</button>   
Step 3 - Now, call this FileContentResult method from your View(.cshtml). Make the jQuery logic of your View page so when you click this button, it calls this jQuery logic.
  1. <script>  
  2.     function ExportToPDF() {  
  3.         var exportURL = getRootUrl() + "YourControllerName/ExportPDF?type=" + type;  
  4.         window.location.href = exportURL;  
  5.     }  
  6.   
  7.     function getRootUrl() {  
  8.         return window.location.origin ? window.location.origin + '/' : window.location.protocol + '/' + window.location.host + '/';  
  9.     }  
  10. </script>   
Step 4 - Create a new FileContentResult method. This method returns a file; so call this method from your View page.
  1. public FileContentResult ExportPDF()    
  2. {    
  3.      
  4.         // creating data table and adding dummy data  
  5.         DataTable dt = new DataTable();  
  6.         dt.Columns.Add("Name");  
  7.         dt.Columns.Add("Branch");  
  8.         dt.Columns.Add("Officer");  
  9.         dt.Columns.Add("CustAcct");  
  10.         dt.Columns.Add("Grade");  
  11.         dt.Columns.Add("Rate");  
  12.         dt.Columns.Add("OrigBal");  
  13.         dt.Columns.Add("BookBal");  
  14.         dt.Columns.Add("Available");  
  15.         dt.Columns.Add("Effective");  
  16.         dt.Columns.Add("Maturity");  
  17.         dt.Columns.Add("Collateral");  
  18.         dt.Columns.Add("LoanSource");  
  19.         dt.Columns.Add("RBCCode");  
  20.   
  21.         dt.Rows.Add(new object[] { "James Bond, LLC", 120, "Garrison Neely""123 3428749020", 35, "6.000""$24,590""$13,432",  
  22.             "$12,659""12/13/21""1/30/27", 55, "ILS""R"});  
  23.   
  24.         ds.Tables.Add(dt);  
  25.    
  26.    
  27.         byte[] filecontent = exportpdf(dt);    
  28.         string filename = "Sample_PDF_" + DateTime.Now.ToString("MMddyyyyhhmmss") + ".pdf";    
  29.         return File(filecontent, ExcelExportHelper.ExcelContentType, filename);    
  30. }    
Now, create a new function like exportpdf(). This function returns bytes.
  1. private byte[] exportpdf(DataTable  dtEmployee )  
  2.     {  
  3.           
  4.         // creating document object  
  5.         System.IO.MemoryStream ms = new System.IO.MemoryStream();  
  6.         iTextSharp.text.Rectangle rec = new iTextSharp.text.Rectangle(PageSize.A4);  
  7.         rec.BackgroundColor = new BaseColor(System.Drawing.Color.Olive);  
  8.         Document doc = new Document(rec);  
  9.         doc.SetPageSize(iTextSharp.text.PageSize.A4);  
  10.         PdfWriter writer = PdfWriter.GetInstance(doc, ms);  
  11.         doc.Open();  
  12.           
  13.         //Creating paragraph for header  
  14.         BaseFont bfntHead = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);  
  15.         iTextSharp.text.Font fntHead = new iTextSharp.text.Font(bfntHead, 16, 1, iTextSharp.text.BaseColor.BLUE);  
  16.         Paragraph prgHeading = new Paragraph();  
  17.         prgHeading.Alignment = Element.ALIGN_LEFT;  
  18.         prgHeading.Add(new Chunk("Dynamic Report PDF".ToUpper(), fntHead));  
  19.         doc.Add(prgHeading);  
  20.   
  21.         //Adding paragraph for report generated by  
  22.         Paragraph prgGeneratedBY = new Paragraph();  
  23.         BaseFont btnAuthor = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);  
  24.         iTextSharp.text.Font fntAuthor = new iTextSharp.text.Font(btnAuthor, 8, 2, iTextSharp.text.BaseColor.BLUE);  
  25.         prgGeneratedBY.Alignment = Element.ALIGN_RIGHT;  
  26.         //prgGeneratedBY.Add(new Chunk("Report Generated by : ASPArticles", fntAuthor));  
  27.         //prgGeneratedBY.Add(new Chunk("\nGenerated Date : " + DateTime.Now.ToShortDateString(), fntAuthor));  
  28.         doc.Add(prgGeneratedBY);  
  29.   
  30.         //Adding a line  
  31.         Paragraph p = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, iTextSharp.text.BaseColor.BLACK, Element.ALIGN_LEFT, 1)));  
  32.         doc.Add(p);  
  33.   
  34.         //Adding line break  
  35.         doc.Add(new Chunk("\n", fntHead));  
  36.   
  37.         //Adding  PdfPTable  
  38.         PdfPTable table = new PdfPTable(dtEmployee.Columns.Count);  
  39.   
  40.         for (int i = 0; i < dtEmployee.Columns.Count; i++)  
  41.         {  
  42.             string cellText = Server.HtmlDecode(dtEmployee.Columns[i].ColumnName);  
  43.             PdfPCell cell = new PdfPCell();  
  44.             cell.Phrase = new Phrase(cellText, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 10, 1, new BaseColor(System.Drawing.ColorTranslator.FromHtml("#000000"))));  
  45.             cell.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#C8C8C8"));  
  46.             //cell.Phrase = new Phrase(cellText, new Font(Font.FontFamily.TIMES_ROMAN, 10, 1, new BaseColor(grdStudent.HeaderStyle.ForeColor)));  
  47.             //cell.BackgroundColor = new BaseColor(grdStudent.HeaderStyle.BackColor);  
  48.             cell.HorizontalAlignment = Element.ALIGN_CENTER;  
  49.             cell.PaddingBottom = 5;  
  50.             table.AddCell(cell);  
  51.         }  
  52.   
  53.         //writing table Data  
  54.         for (int i = 0; i < dtEmployee.Rows.Count; i++)  
  55.         {  
  56.             for (int j = 0; j < dtEmployee.Columns.Count; j++)  
  57.             {  
  58.                 table.AddCell(dtEmployee.Rows[i][j].ToString());  
  59.             }  
  60.         }  
  61.   
  62.         doc.Add(table);  
  63.         doc.Close();  
  64.           
  65.         byte[] result = ms.ToArray();  
  66.         return result;  
  67.           
  68.     }  
Conclusion
 
In this article, I explained how to create a PDF file using your C# DataTable and how to download it.