Windows Forms: How to Export DataTable to PDF in C#

This post shows you How to Export data from DataTable to PDF using iTextSharp in C# Windows Forms Application.

Dragging DataGridView, Button from your Visual Studio toolbox into your form designer, then design a simple UI allows you to export data from DataTable to PDF file in c# as shown below.

Export datatable to pdf in c# windows application

c# export datatable to pdf

Adding a bindingsource to your DataGridView to retrieve data from customer table in the Northwind database.

private void frmExportDataTableToPdf_Load(object sender, EventArgs e)
{
    // TODO: This line of code loads data into the 'appData.Customers' table. You can move, or remove it, as needed.
    this.customersTableAdapter.Fill(this.appData.Customers);
}

Export to pdf in c# using itextsharp

Right-clicking on your project, then select Manage Nuget Packages from your Visual Studio.

Next, Search 'iTextSharp', then download and install it.

c# itextsharp

iTextSharp is an open source library helps you to handle pdf file.

Adding a click event handler to the Export button allows you to export datatable to pdf file in c#.

private void btnExportData_Click(object sender, EventArgs e)
{
    using (SaveFileDialog sfd = new SaveFileDialog() { Filter = "PDF files|*.pdf" })
    {
        if (sfd.ShowDialog() == DialogResult.OK)
        {
            try
            {
                Document doc = new Document(iTextSharp.text.PageSize.A4, 10, 10, 42, 35);
                PdfWriter pdfWriter = PdfWriter.GetInstance(doc, new FileStream(sfd.FileName, FileMode.Create));
                doc.Open();
                PdfContentByte pdfContent = pdfWriter.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;
                pdfContent.SetColorStroke(BaseColor.WHITE);//setting the color of the border to white
                pdfContent.Rectangle(rectangle.Left, rectangle.Bottom, rectangle.Width, rectangle.Height);
                pdfContent.Stroke();
                //setting font type, font size and font color
                iTextSharp.text.Font headerFont = iTextSharp.text.FontFactory.GetFont(FontFactory.TIMES_ROMAN, 25, BaseColor.LIGHT_GRAY);
                Paragraph p = new Paragraph();
                p.Alignment = Element.ALIGN_CENTER;//adjust the alignment of the heading
                p.Add(new Chunk("Customers", headerFont));//adding a heading to the PDF
                doc.Add(p);//adding component to the document
                iTextSharp.text.Font font = iTextSharp.text.FontFactory.GetFont(FontFactory.TIMES_ROMAN, 12, BaseColor.LIGHT_GRAY);
                //creating pdf table
                PdfPTable table = new PdfPTable(dataGridView1.Columns.Count);
                for (int j = 0; j < dataGridView.Columns.Count; j++)
                {
                    PdfPCell cell = new PdfPCell(); //create object from the pdfpcell
                    cell.BackgroundColor = BaseColor.WHITE;//set color of cells
                    cell.AddElement(new Chunk(dataGridView.Columns[j].HeaderText.ToUpper(), font));
                    table.AddCell(cell);
                }
                //adding rows from gridview to table
                for (int i = 0; i < dataGridView.Rows.Count; i++)
                {
                    table.WidthPercentage = 100;//set width of the table
                    for (int j = 0; k < dataGridView.Columns.Count; j++)
                    {
                        if (dataGridView1[j, i].Value != null)
                            table.AddCell(new Phrase(dataGridView[j, i].Value.ToString()));
                    }
                }
                //adding table to document
                doc.Add(table);
                doc.Close();
                MessageBox.Show("You have successfully exported the file.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}

Through c# example, I showed you how to create a pdf file with itextsharp in c#, then write data from datatable into pdf file using itextsharp in c# windows forms application.

Related