In this article, we will discuss how to export data in a dataTable to a PDF file format using C#. It is a common question that comes to every programmer after populating their tables from the database, how can we export this table into PDF? The answer is pretty clear. We can do this easily using the iTextSharp library in C#.

What is the iTextSharp library?

iText is an open source library available free for personal use.  This PDF library allows creating PDF files from the tables with customized styles. To incorporate iTextSharp into our project, we need to download the .dll files from the nuget.org. After downloading the package, we need to import “itextsharp.dll” and “itextsharp.pdfa.dll” to the C# project.

Download iTextSharp from here: https://www.nuget.org/packages/iTextSharp/5.5.13

Or we can install the library from the .NET CLI using the below command;

            dotnet add package iTextSharp –version 5.5.13

After downloading and importing the required files, the first thing we have to do is to import 2 libraries to our C# project.  Then add the following namespace to your code

using iTextSharp.text;
using iTextSharp.text.pdf;

Set up the document

Next thing we have to do is to set the page size of the PDF. There are several sizes we can use with the iText library. For an example, we can use A4, A3, A6, Letter etc. as we wish. Further details about page sizes can be found on the official documentation of the iText. Link to it is given below for further reading.

http://itextsupport.com/apidocs/iText5/5.5.13-SNAPSHOT/com/itextpdf/text/PageSize.html

In this example, I am going to use the Letter page sizing with customized margins. For that, we need to create a document object as we are going to create a PDF from scratch.

Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);

After creating the document object, we need to specify the new pdf by creating a PdfWriter instance by applying the custom size document we created earlier. For that iText provides a default method which takes 2 arguments; one which is the document object we created and the other one is the new file stream.

PdfWriter w = PdfWriter.GetInstance(doc, new FileStream(@"employees.pdf", FileMode.Create));

By using FileMode.Create property, we tell the PDF writer to create a new PDF document with the custom sizes we provided and rename the new PDF to “employees.pdf”. In here we use @ symbol to make sure that new PDF is created in the absolute location of the project; i.e. is the bin directory. But if you want to create it in a different location, we can specify the relative path as well.

Set the borders

So far we have created an empty pdf file. Now let’s add some borders to it, to make it look nice. For that, we can use the Rectangle object provided by the iTextSharp.

                //Add border to page
                PdfContentByte content = w.DirectContent;
                iTextSharp.text.Rectangle rectangle = new iTextSharp.text.Rectangle(doc.PageSize);
	    //customized border sizes
                rectangle.Left += doc.LeftMargin - 5;
                rectangle.Right -= doc.RightMargin - 5;
                rectangle.Top -= doc.TopMargin - 5;
                rectangle.Bottom += doc.BottomMargin - 5;
                content.SetColorStroke(BaseColor.BLACK); // setting the color of the border to black
                content.Rectangle(rectangle.Left, rectangle.Bottom, rectangle.Width, rectangle.Height);
                content.Stroke();

Do some customization

By now we have added a border to our PDF. The great thing about this library is that we can customize everything as we wish. Next, we will set the font styles of the document and add a logo to the pdf file. For each of these iTextSharp provides default methods and we can use them and do the customization as we wish. Now let’s see how we can customize the font and logo of the pdf.

//setting font type, font size and font color
    iTextSharp.text.Font font = iTextSharp.text.FontFactory.GetFont(
FontFactory.TIMES_ROMAN, 30, BaseColor.BLUE);
                Paragraph prg = new Paragraph();
                prg.Alignment = Element.ALIGN_CENTER; // adjust the alignment of the heading
                prg.Add(new Chunk("Employee List", font)); //adding a heading to the PDF
                doc.Add(prg); //add the component we created to the document


                //specify the location of the logo
                iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(
                                                                    @"msmsIcon1.png");
                image.Alignment = iTextSharp.text.Image.ALIGN_LEFT; //image alignments
                image1.ScaleToFit(60f, 60f); //setting the width and height of the image
                doc.Add(image);

Load the data

Next section is the most important part of the exporting. We need to specify the DataTable that we are going to export to the PDF file. For that, we will create an object from the PdfPTable and assign the number of columns in the DataTable.

   PdfPTable table = new PdfPTable(tblemp.Columns.Count);

After that, we need to create table cells for each of the columns we specified. To create table cells we use PdfPCell class provided by the iTextSharp.

             for (int j = 0; j < tblemp.Columns.Count; j++)
             {
                    PdfPCell cell = new PdfPCell(); //create object from the pdfpcell class
                    cell.BackgroundColor = BaseColor.LIGHT_GRAY; //set color of cells to gray
                    cell.AddElement(new Chunk(tblemp.Columns[j].HeaderText.ToUpper(), 
                                               fonth));
                    table.AddCell(cell);
               }

Since we have created the full structure of the PDF file, now it’s time to fill the table in the PDF file. For that, we need to iterate through the data of the dataTable and insert them into the document.

Note: it is really important to close the document as it can cause stack overflow errors unless it is closed at the end.
                //add actual rows from grid to table
                for (int i = 0; i < tblemp.Rows.Count; i++)
                {
                    table.WidthPercentage = 100; //set width of the table
                    for (int k = 0; k < tblemp.Columns.Count; k++)
                    {
                        if (tblemp [k, i].Value != null)
                            // get the value of   each cell in the dataTable tblemp
                            table.AddCell(new Phrase(tblemp [k, i].Value.ToString()));                        
                    }
                }

                //add the table to document
                doc.Add(table);
                doc.Close();

We can use this code inside a method and call it from anywhere you want. For an example, we can call the method to a click event of a button and export the data into PDF file and save it in a path you specified. Nevertheless, iTextSharp library is considered to be the easiest way of exporting dataTables into PDF in C#.

Related Articles

JSON Serialization and Deserialization in C#

Introduction to Stack in C#

Bind Countries to a DropDownList in ASP.NET using C#

 

Last modified: February 21, 2019

Comments

Write a Reply or Comment

Your email address will not be published.