Aug 15

Export Data to PDF using C#

In this article I would like to show how to export datatable to PDF (Portable Document Format) File. To create PDF file, we need to write data to Response object of HttpContext. The content type used should be “application/pdf”
PDF file extension is not similar to what we discussed in Export data to CSV. Here I will create file in windows temp (Run > %temp%) folder and write data into it. Later I will user TransmitFile() function of Response object to download.
What is iTextSharp?
iText is open source PDF library available through nuget allows you to CREATE, ADAPT, INSPECT and MAINTAIN documents in the Portable Document Format (PDF), allowing you to add PDF functionality to your software projects with ease
So I will use iTextSharp library to create PDF file.
Other Export Articles
 
So let’s start with implementation in C# now,
Before starting implementation first install iTextSharp library from nugget package manager console or user interface provided with visual studio.
Command: Install-Package iTextSharp -Version 5.5.11
Step 1: Create plain employee class with some fields in it.
public class Employee
    {
        public int EmployeeId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public bool Gender { get; set; }
        public DateTime Dob { get; set; }
        public string Title { get; set; }
        public string Department { get; set; }
    }
Step 2: Create helper class which defines function to export data from datatable to PDF format.
 
using System.IO;
using System.Data;
using iTextSharp.text;
using iTextSharp.text.pdf;
public class PdfExportHelper
    {
        public string ExportToPdf(string fileName, DataTable dataTable)
        {
            var pdfDocument = new Document();
            var pdfFile = string.Format(“{0}{1}.pdf”, Path.GetTempPath(), fileName);
            //if exist then delete and create new
            if (File.Exists(pdfFile))
            {
                File.Delete(pdfFile);
            }
            var pdfWriter = PdfWriter.GetInstance(pdfDocument, new FileStream(pdfFile, FileMode.Create));
            pdfDocument.Open();
            var pdfPTable = new PdfPTable(dataTable.Columns.Count);
            pdfPTable.WidthPercentage = 100;
            //Set columns names in the pdf file
            for (int k = 0; k < dataTable.Columns.Count; k++)
            {
                var pdfPCell = new PdfPCell(new Phrase(dataTable.Columns[k].ColumnName));
                pdfPCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                pdfPCell.VerticalAlignment = PdfPCell.ALIGN_CENTER;
                pdfPCell.BackgroundColor = new BaseColor(51, 102, 102);
                pdfPTable.AddCell(pdfPCell);
            }
            //Add values of DataTable in pdf file
            for (int row = 0; row < dataTable.Rows.Count; row++)
            {
                for (int column = 0; column < dataTable.Columns.Count; column++)
                {
                    var cell = new PdfPCell(new Phrase(dataTable.Rows[row][column].ToString()));
                    //Align the cell in the center
                    cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                    cell.VerticalAlignment = PdfPCell.ALIGN_CENTER;
                    pdfPTable.AddCell(cell);
                }
            }
            pdfDocument.Add(pdfPTable);
            pdfDocument.Close();
            return pdfFile;
        }
    }
 
 
Step 3: Question comes to your mind, how to use this. Call below functions from your ASP.NET event handler or ASP.NET MVC action method.
 
private void ExportTableToPdf(SearchBase searchModel)
        {
            var employeeDataTable = _employeeBal.GetAllDataTable(searchModel);
            var pdfExportHelper = new PdfExportHelper();
            var filePath = pdfExportHelper.ExportToPdf(“Employee”, employeeDataTable);
            var file = new FileInfo(filePath);
            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader(“content-disposition”, “attachment;filename=Employee.pdf”);
            Response.Charset = “”;
            Response.ContentType = “Application/pdf”;
            Response.TransmitFile(file.FullName);
            Response.End();
        }
I hope you enjoyed this article and you can use same code in your assignment or project.

 

2 comments

  1. Very helpful codes! for beginners and want to save time I found zetpdf.com i heard a lot of this from my co workers

  2. i have same issue …. there is simple solution visit http://zetpdf.com/

Leave a Reply