In this article I will explain with an example, how to export DataGridView to Password Protected (Secured) PDF using iTextSharp library in Windows Forms (WinForms) Application with C# and VB.Net.
 
 

Download iTextSharp and XmlWorkerHelper Libraries

In order to install iTextSharp and XmlWorkerHelper library from Nuget, please refer the following articles.
 
 

Form Design

The following Form consists of:
DataGridView – For displaying data.
Button – For exporting PDF.
The Button has been assigned with a Click event handler.
Export DataGridView to Password Protected ( Secured ) PDF using iTextSharp in C# and VB.Net
 
 

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;
 
VB.Net
Imports System.IO
Imports System.Data
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports iTextSharp.tool.xml
 
 

Binding DataGridView using C# and VB.Net

Inside the Form_Load event handler, the BindDataGridView method is called.
Inside the BindDataGridView method, first the connection string is read from the App.Config file.
Note: For more details on how to read connection string from App.Config, file please refer my article Read (Get) Connection String from App.Config file using C# and VB.Net.
 
Then, a connection to the database is established using the SqlConnection class.
The SqlDataAdapter object is initialized with the SqlCommand and using the Fill function, the DataTable is populated with the records from database.
Finally, the DataTable is assigned to the DataSource property of DataGridView and the DataGridView is populated.
C#
private void Form1_Load(object sender, EventArgs e)
{
    this.BindDataGridView();
}
 
private void BindDataGridView()
{
    string sql "SELECT TOP 10 CustomerID, ContactName, Country FROM Customers";
    string constr ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlDataAdapter sda = new SqlDataAdapter(sql, con))
        {
            using (DataTable dt = new DataTable())
            {
                sda.Fill(dt);
                dataGridView1.DataSource = dt;
            }
        }
    }
}
 
VB.Net
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Me.BindDataGridView()
End Sub
 
Private Sub BindDataGridView()
    Dim sql As String "SELECT TOP 10 CustomerID, ContactName, Country FROM Customers"
    Dim constr As String ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As New SqlConnection(constr)
        Using sda As New SqlDataAdapter(sql, con)
            Using dt As New DataTable()
                sda.Fill(dt)
                dataGridView1.DataSource = dt
            End Using
        End Using
    End Using
End Sub
 
 

Exporting GridView to Password Protected ( Secured ) PDF using iTextSharp in C# and VB.Net

When the Export Button is clicked, an HTML Table is generated by concatenating string and data is read from DataGridView using FOR EACH loop.
Then, the BYTE array is created and set to NULL.
After that, the iTextSharp PDF document is created using Document class and the data is written using ParseXHtml method of XmlWorkerHelper class which converts it to PDF document and saves it to the MemoryStream class object.
Then, a check is performed whether the Folder (Directory) where PDF file will be saved exists or not, if not then it is created.
Another MemoryStream class object is created which is used for making PDF Password Protected using the Encrypt method of PDFEncryptor class and the result is saved in the output MemoryStream objects.
Note: The Encrypt method accepts the password as parameter.
 
Finally, the PDF file is saved at the specified location using WriteAllBytes method of File class.
C#
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>";
 
    //Exporting HTML to PDF file.
    byte[] bytes = null;
    using (MemoryStream memoryStream = new MemoryStream())
    {
        StringReader sr = new StringReader(html);
        Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);
        PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream);
        pdfDoc.Open();
        XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr);
        pdfDoc.Close();
        bytes memoryStream.ToArray();
    }
 
    //Creating Folder for saving PDF.
    string folderPath  "C:\\PDFs\\";
    if (!Directory.Exists(folderPath))
    {
        Directory.CreateDirectory(folderPath);
    }
 
    //Adding password to PDF.
    using (MemoryStream output = new MemoryStream())
    {
        string password = "pass@123";
        PdfReader reader = new PdfReader(bytes);
        PdfEncryptor.Encrypt(reader, output, true, password, password, PdfWriter.ALLOW_SCREENREADERS);
        File.WriteAllBytes(folderPath + "DataGridViewExport.pdf", output.ToArray());
    }
}
 
VB.Net
Private Sub btnExportPDF_Click(sender As System.Object, e As System.EventArgs) Handles btnExportPDF.Click
    'Table start.
    Dim html As String "<table cellpadding='5' cellspacing='0' style='border: 1px solid #ccc;font-size: 9pt'>"
 
    'Adding HeaderRow.
    html &= "<tr>"
 
    For Each column As DataGridViewColumn In dataGridView1.Columns
        html &= "<th style='background-color: #B8DBFD;border: 1px solid #ccc'>" & column.HeaderText & "</th>"
    Next
    html &= "</tr>"
 
    'Adding DataRow.
    For Each row As DataGridViewRow In dataGridView1.Rows
        html &= "<tr>"
 
        For Each cell As DataGridViewCell In row.Cells
            html &= "<td style='width:120px;border: 1px solid #ccc'>" & cell.Value.ToString() & "</td>"
        Next
 
        html &= "</tr>"
    Next
 
    'Table end.
    html &= "</table>"
 
    Dim bytes As Byte() = Nothing
    Using memoryStream As MemoryStream = New MemoryStream()
        Dim sr As StringReader = New StringReader(html)
        Dim pdfDoc As Document = New Document(PageSize.A4, 10.0F, 10.0F, 100.0F, 0F)
        Dim writer As PdfWriter PdfWriter.GetInstance(pdfDoc, memoryStream)
        pdfDoc.Open()
        XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr)
        pdfDoc.Close()
        bytes memoryStream.ToArray()
    End Using
 
    'Creating Folder for saving PDF.
    Dim folderPath As String "C:\PDFs\"
    If Not Directory.Exists(folderPath) Then
        Directory.CreateDirectory(folderPath)
    End If
 
    'Exporting HTML to PDF file.
    Using output As MemoryStream = New MemoryStream()
        Dim password As String "pass@123"
        Dim reader As PdfReader = New PdfReader(bytes)
        PdfEncryptor.Encrypt(reader, output, True, password, password, PdfWriter.ALLOW_SCREENREADERS)
        File.WriteAllBytes(folderPath & "DataGridViewExport.pdf", output.ToArray())
    End Using
End Sub
 
 

Screenshots

The Form

Export DataGridView to Password Protected ( Secured ) PDF using iTextSharp in C# and VB.Net
 

Exported PDF

Export DataGridView to Password Protected ( Secured ) PDF using iTextSharp in C# and VB.Net
 
 

Downloads