Export HTML to PDF in Windows Forms Application using iTextSharp


In this article I will explain with an example, how to export HTML to PDF in Windows Forms Application using iTextSharp, C# and VB.Net.
First a DataGridView will be populated with some data and then an HTML Table will be generated using the values from the DataGridView.
Finally, the HTML Table will be exported and saved as PDF file using iTextSharp and XMLWorkerHelper class in Windows Forms Application with C# and VB.Net.


Form Design
The Form Design consists of a DataGridView and a Button.




Namespaces
You will need to import the following namespaces.
C#
using System.IO;
using System.Data;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
Populating DataGridView Inside the Form Constructor, the DataGridView is populated with a dynamic DataTable populated with some dummy data.

public Form1()
{
    InitializeComponent();
    this.BindDataGridView();
}
 
private void BindDataGridView()
{
    DataTable dt = new DataTable();
    dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id"typeof(int)),
            new DataColumn("Name"typeof(string)),
            new DataColumn("Country",typeof(string)) });
    dt.Rows.Add(1, "John Hammond""United States");
    dt.Rows.Add(2, "Mudassar Khan""India");
    dt.Rows.Add(3, "Suzanne Mathews""France");
    dt.Rows.Add(4, "Robert Schidner""Russia");
    this.dataGridView1.DataSource = dt;
}


Exporting HTML to PDF using iTextSharp in Windows Forms Application
When the Export Button is clicked, an HTML Table is created with string concatenation.
The HTML Table will contain columns same as that of the DataGridView and then a loop is executed over the DataGridView columns to add their header texts to the Header row of the HTML Table.
Once the Header row is populated then loop is executed over the DataGridView rows to add data rows to the HTML Table.
Then a check is performed to verify whether the Folder (Directory) to save the PDF file exists. If it does not exists then the Folder (Directory) is created.
Finally, the HTML string is converted to PDF document using XMLWorkerHelper class and the PDF file is saved in the Folder (Directory) on disk.


private void btnExportPdf_Click(object sender, EventArgs e)
{
    //Table start.
    string html = "<table cellpadding='5' cellspacing='0' style='border:                     1px solid #ccc;font-size: 9pt'>";
 
    //Adding HeaderRow.
    html += "<tr>";
    foreach (DataGridViewColumn column in dataGridView1.Columns)
    {
        html += "<th style='background-color: #B8DBFD;border: 1px solid                   #ccc'>" + column.HeaderText + "</th>";
    }
    html += "</tr>";
 
    //Adding DataRow.
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        html += "<tr>";
        foreach (DataGridViewCell cell in row.Cells)
        {
            html += "<td style='width:120px;border: 1px solid #ccc'>" +                         cell.Value.ToString() + "</td>";
        }
        html += "</tr>";
    }
 
    //Table end.
    html += "</table>";
 
    //Creating Folder for saving PDF.
    string folderPath = "C:\\PDFs\\";
    if (!Directory.Exists(folderPath))
    {
        Directory.CreateDirectory(folderPath);
    }
 
    //Exporting HTML to PDF file.
    using (FileStream stream = new FileStream(folderPath       + "DataGridViewExport.pdf"FileMode.Create))
    {
        Document pdfDoc = new Document(PageSize.A2, 10f, 10f, 10f, 0f);
        PdfWriter writer = PdfWriter.GetInstance(pdfDoc, stream);         
        pdfDoc.Open();
        StringReader sr = new StringReader(html);
        XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr);
        pdfDoc.Close();
        stream.Close();
    }
}

 
Screenshots
The DataGridView


The Exported PDF file


Comments

Post a Comment