In this article I will explain with an example, how to export ASP.Net GridView to Password Protected (Secured) PDF using iTextSharp Library in ASP.Net with C# and VB.Net.
 
 
Database
For this article I am making use of the Microsoft’s Northwind Database. Download and install instructions are provided in the link below.
 
HTML Markup
The HTML Markup consists of an ASP.Net GridView and a Button.
<asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
    RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000"
    runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="ContactName" HeaderText="Contact Name" ItemStyle-Width="150px" />
        <asp:BoundField DataField="City" HeaderText="City" ItemStyle-Width="100px" />
        <asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="100px" />
    </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.html.simpleparser;
using iTextSharp.text.pdf;
 
VB.Net
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports iTextSharp.text
Imports iTextSharp.text.html.simpleparser
Imports iTextSharp.text.pdf
 
 
Binding the GridView
Below is the code to bind the GridView with records from the Customers table of the Northwind database.
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        this.BindGrid();
    }
}
 
private void BindGrid()
{
    string strConnString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(strConnString))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT TOP 10 * FROM Customers"))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    GridView1.DataSource = dt;
                    GridView1.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 strConnString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As New SqlConnection(strConnString)
        Using cmd As New SqlCommand("SELECT TOP 10 * FROM Customers")
            Using sda As New SqlDataAdapter()
                cmd.Connection = con
                sda.SelectCommand = cmd
                Using dt As New DataTable()
                    sda.Fill(dt)
                    GridView1.DataSource = dt
                    GridView1.DataBind()
                End Using
            End Using
        End Using
    End Using
End Sub
 
Export GridView to Password Protected ( Secured ) PDF using iTextSharp in ASP.Net
 
 
Exporting ASP.Net GridView to Password Protected PDF
This code is bit different from the normal GridView export to PDF. Firstly instead of creating the iTextSharp PDF Document in the Response Stream, it has been created in a new Memory Stream object.
Then the Memory Stream is converted into array of bytes, to start the process of Password Protection.
Then two new Memory Stream objects are created i.e. input and output. The input Memory Stream object is used for the Password Protecting the GridView Export PDF using the iTextSharp PDFEncryptor class and the result is saved in the output Memory Stream objects which is then finally sent to the browser Response Stream.
C#
protected void ExportToPDF(object sender, EventArgs e)
{
    using (StringWriter sw = new StringWriter())
    {
        using (HtmlTextWriter hw = new HtmlTextWriter(sw))
        {
            //To Export all pages
            GridView1.AllowPaging = false;
            this.BindGrid();
 
            GridView1.RenderControl(hw);
            StringReader sr = new StringReader(sw.ToString());
            Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
            HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
            using (MemoryStream memoryStream = new MemoryStream())
            {
                PdfWriter.GetInstance(pdfDoc, memoryStream);
                pdfDoc.Open();
                htmlparser.Parse(sr);
                pdfDoc.Close();
                byte[] bytes = memoryStream.ToArray();
                memoryStream.Close();
                using (MemoryStream input = new MemoryStream(bytes))
                {
                    using (MemoryStream output = new MemoryStream())
                    {
                        string password = "pass@123";
                        PdfReader reader = new PdfReader(input);
                        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();
                    }
                }
            }
        }
    }
}
 
public override void VerifyRenderingInServerForm(Control control)
{
    /* Verifies that the control is rendered */
}
 
VB.Net
Protected Sub ExportToPDF(sender As Object, e As EventArgs)
    Using sw As New StringWriter()
        Using hw As New HtmlTextWriter(sw)
            'To Export all pages
            GridView1.AllowPaging = False
            Me.BindGrid()
 
            GridView1.RenderControl(hw)
            Dim sr As New StringReader(sw.ToString())
            Dim pdfDoc As New Document(PageSize.A2, 10.0F, 10.0F, 10.0F, 0.0F)
            Dim htmlparser As New HTMLWorker(pdfDoc)
            Using memoryStream As New MemoryStream()
                PdfWriter.GetInstance(pdfDoc, memoryStream)
                pdfDoc.Open()
                htmlparser.Parse(sr)
                pdfDoc.Close()
                Dim bytes As Byte() = memoryStream.ToArray()
                memoryStream.Close()
                Using input As New MemoryStream(bytes)
                    Using output As New MemoryStream()
                        Dim password As String = "pass@123"
                        Dim reader As New PdfReader(input)
                        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 Using
            End Using
        End Using
    End Using
End Sub
 
Public Overrides Sub VerifyRenderingInServerForm(control As Control)
    ' Verifies that the control is rendered
End Sub
 
Export GridView to Password Protected ( Secured ) PDF using iTextSharp in ASP.Net
Note: When the PDF File is opened you will see the word (Secured) next to the File name in the Title Bar of Adobe Reader. This means that your PDF is Secured and Password Protected.
 
Export GridView to Password Protected ( Secured ) PDF using iTextSharp in ASP.Net
 
 
Demo
 
 
Downloads