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

Download iTextSharp and XmlWorkerHelper Libraries

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

HTML Markup

The HTML Markup consists of following controls:
GridView – For displaying data.

Columns

The GridView consists of three BoundField columns.
Button – For exporting PDF.
The Button has been assigned with a OnClick event handler.
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false" HeaderStyle-BackColor="#3AC0F2"
    RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000">
    <Columns>
        <asp:BoundField DataField="ContactName" HeaderText="Contact Name" />
        <asp:BoundField DataField="City" HeaderText="City" />
        <asp:BoundField DataField="Country" HeaderText="Country" />
    </Columns>
</asp:GridView>
<br />
<asp:Button ID="btnExport" runat="server" Text="Export To PDF" OnClick="ExportToPDF" />
 
 

Namespaces

You will need to import the following namespaces.
C#
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
 
VB.Net
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports iTextSharp.tool.xml
 
 

Binding GridView using C# and VB.Net

Inside the Page_Load event handler, the BindGrid method is called.
Inside the BindGrid method, first the connection string is read from the Web.Config file.
Note: For more details on how to read connection string from Web.Config file, please refer my article Read or Write Connection Strings in Web.Config file using ASP.Net 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 GridView and the GridView is populated.
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        this.BindGrid();
    }
}
 
private void BindGrid()
{
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    string sql "SELECT TOP 10 * FROM Customers";
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlDataAdapter sda = new SqlDataAdapter(sql, con))
        {
            using (DataTable dt = new DataTable())
            {
                sda.Fill(dt);
                gvCustomers.DataSource = dt;
                gvCustomers.DataBind();
            }
        }
    }
}
 
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    If Not IsPostBack Then
        Me.BindGrid()
    End If
End Sub
 
Private Sub BindGrid()
    Dim constr As String ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Dim sql As String "SELECT TOP 10 * FROM Customers"
    Using con As SqlConnection = New SqlConnection(constr)
        Using sda As SqlDataAdapter = New SqlDataAdapter(sql, con)
            Using dt As DataTable = New DataTable()
                sda.Fill(dt)
                gvCustomers.DataSource = dt
                gvCustomers.DataBind()
            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, the BYTE array is created and set to NULL.
The StringWriter and HtmlTextWriter objects are created and AllowPaging property of the GridView is set to FALSE and the BindGrid method is called.
Then, the GridView is rendered into an HTML string using RenderControl which accepts HtmlTextWriter class object as parameter.
After that, the generated HTML is added to the iTextSharp PDF document using Document class.
The PDF document is opened and the GridView data is written using ParseXHtml method of XmlWorkerHelper class which converts it to PDF document and saves it to the MemoryStream class object.
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.
Then, the Response class properties are set.
1. ContentType – It informs the Browser about the file type. In this case it is PDF file.
2. Content-Disposition – It is a response header indicating, the download file is an attachment and allows setting the file name.
Note: For more details on Content Disposition Header, please refer my article What is Content Disposition Header in ASP.Net.
 
Finally, Document class object is written to the Response which initiates the File download operation.
C#
protected void ExportToPDF(object sender, EventArgs e)
{
    byte[] bytes = null;
    using (StringWriter sw = new StringWriter())
    {
        using (HtmlTextWriter hw  =  new HtmlTextWriter(sw))
        {
            // To Export all pages.
            gvCustomers.AllowPaging = false;
            this.BindGrid();
 
            gvCustomers.RenderControl(hw);
            StringReader sr = new StringReader(sw.ToString());
            Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
            using (MemoryStream memoryStream = new MemoryStream())
            {
                PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream);
                pdfDoc.Open();
                XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc,sr);
                pdfDoc.Close();
                bytes = memoryStream.ToArray();
                memoryStream.Close();
            }
        }
    }
 
    // 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);
        bytes = output.ToArray();
 
        Response.ContentType "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.BinaryWrite(bytes);
        Response.End();
    }
}
 
VB.Net
Protected Sub ExportToPDF(sender As Object, e As EventArgs)
    Dim bytes As Byte() = Nothing
    Using sw As StringWriter = New StringWriter()
        Using hw As HtmlTextWriter = New HtmlTextWriter(sw)
 
            ' To Export all pages.
            gvCustomers.AllowPaging = False
            Me.BindGrid()
 
            gvCustomers.RenderControl(hw)
            Dim sr As StringReader = New StringReader(sw.ToString())
            Dim pdfDoc As Document = New Document(PageSize.A4, 10.0F, 10.0F, 10.0F, 0F)
            Using memoryStream As MemoryStream = New MemoryStream()
                Dim writer As PdfWriter PdfWriter.GetInstance(pdfDoc,memoryStream)
                pdfDoc.Open()
                XMLWorkerHelper.GetInstance().ParseXHtml(writer,pdfDoc,sr)
                pdfDoc.Close()
                bytes = memoryStream.ToArray()
                memoryStream.Close()
            End Using
        End Using
    End Using
 
    ' Adding password to PDF.
    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)
        bytes = output.ToArray()
 
        Response.ContentType "application/pdf"
        Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf")
        Response.Cache.SetCacheability(HttpCacheability.NoCache)
        Response.BinaryWrite(bytes)
        Response.[End]()
    End Using
End Sub
 
 

Screenshots

The Form

Export GridView to Password Protected ( Secured ) PDF using iTextSharp in ASP.Net
 

Exported PDF

Export GridView to Password Protected ( Secured ) PDF using iTextSharp in ASP.Net
 
 

Downloads