Password-Protected PDF File Using ASP.Net C#

Background

There is often a need in a project's reporting module to send the report to a word-protected PDF format. So to satisfy that requirement I decided to write this article, especially focusing on beginners and those who want to learn how to make a word-protected PDF file using ASP.NET C# using itextsharp dll.

Prerequisites

  • To make a word-protected PDF we need to reference itextsharp.dll.
  • Download itextsharp.dll from the internet.

itextsharp.dll is a free DLL available to download that provides some methods to export a Grid View to a PDF file as well as some methods to protect generated files. After adding the reference, use the following references of itextsharp.dll.

using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;

I hope you have done it.

Now before creating the application, let us create a table named employee in a database for showing the records in a GridView. The table has the following fields (shown in the following image).

Employee

I hope you have created the same type of table. Now create the Web Site as.

  1. "Start", "All Programs" "Microsoft Visual Studio 2010".
  2. "File", "New Web site", "C#", and "ASP.NET Empty Web Site" (to avoid adding a master page).
  3. Give the project a name such as wordProtecedPDFDoc or another as you wish and specify the location.
  4. Then right-click on Solution Explorer - "Add New Item" - Default. aspx page.
  5. Add a button, one label, and a Grid View.

Now let us create a function to bind the records to a Grid View from the Database. If you are a beginner and don't know in detail how to bind a Grid View from the database then refer to the following article of mine.

Inserting Form Data Into DataBase and Display In ASP.NET GridView

Now, for this article create the following function in the default. aspx.cs page to bind the Grid View.

private void Bindgrid()
{
    connection();
    query = "select *from Employee"; // not recommended this i have written just for example, write stored procedure for security
    com = new SqlCommand(query, con);
    SqlDataReader dr = com.ExecuteReader();
    GridView1.DataSource = dr;
    GridView1.DataBind();
    con.Close();
}

Now, call the preceding function on page load as.

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        Bindgrid();
    }
}

Now run the application, and then we can see the following records in the Grid View as.

Run the application

Now, we have a record to export into Microsoft Office Word. Let us start coding for our actual requirements. Add the VerifyRenderingInServerForm event after the page load that is required when exporting the Grid View to Excel, Word, and PDF to avoid the runtime error that occurs, such as "GridView' must be placed inside a form tag with runat=server."

public override void VerifyRenderingInServerForm(Control control)
{
    // Required to avoid the runtime error:
    // "Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server."
}

Now before creating the function to export the Grid View to PDF add the reference for itextsharp.dll by right-clicking the Solution Explorer. After adding the reference the Solution Explorer will look such as.

Grid View 

Now create the following function to export the Grid View to word-protect the PDF as.

private void wordProtectedPDF()
{
    StringWriter sw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);
    GridView1.RenderControl(hw);
    StringReader sr = new StringReader(sw.ToString());
    
    Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
    HTMLWorker htmlworker = new HTMLWorker(pdfDoc);
    
    using (MemoryStream ObjememoryStream = new MemoryStream())
    {
        PdfWriter.GetInstance(pdfDoc, ObjememoryStream);
        pdfDoc.Open();
        htmlworker.Parse(sr);
        pdfDoc.Close();
        byte[] Filebytes = ObjememoryStream.ToArray();
        ObjememoryStream.Close();
        
        using (MemoryStream inputData = new MemoryStream(Filebytes))
        {
            using (MemoryStream outputData = new MemoryStream())
            {
                string PDFFileword = "vithal@C#cornerDemo"; // you can also generate Dynamic word
                PdfReader reader = new PdfReader(inputData);
                PdfEncryptor.Encrypt(reader, outputData, true, PDFFileword, PDFFileword, PdfWriter.ALLOW_SCREENREADERS);
                Filebytes = outputData.ToArray();
                Response.ContentType = "application/pdf";
                Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf");
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.BinaryWrite(Filebytes);
                Response.End();
                GridView1.AllowPaging = true;
                GridView1.DataBind();
            }
        }
    }
}

Now call the above method on the export button and click as.

protected void Button1_Click(object sender, EventArgs e)
{
    //calling method to generate word Protected PDF
    wordProtectedPDF();
}

Now the entire code of the Default. aspx.cs page will be as follows.

using System;
using System.Web.UI;
using System.Configuration;
using System.Data.SqlClient;
using System.IO;
using System.Web;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;

public partial class _Default : System.Web.UI.Page
{
    private SqlConnection con;
    private SqlCommand com;
    private string constr, query;

    private void connection()
    {
        constr = ConfigurationManager.ConnectionStrings["getconn"].ToString();
        con = new SqlConnection(constr);
        con.Open();
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Bindgrid();
        }
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
        //required to avoid the runtime error "Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server."
    }

    private void Bindgrid()
    {
        connection();
        query = "select * from Employee"; // not recommended this, I have written just for example, write stored procedure for security
        com = new SqlCommand(query, con);
        SqlDataReader dr = com.ExecuteReader();
        GridView1.DataSource = dr;
        GridView1.DataBind();
        con.Close();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        // calling method to generate word Protected PDF
        wordProtectedPDF();
    }
    private void wordProtectedPDF()
    {
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        GridView1.RenderControl(hw);
        StringReader sr = new StringReader(sw.ToString());

        Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
        HTMLWorker htmlworker = new HTMLWorker(pdfDoc);

        using (MemoryStream ObjememoryStream = new MemoryStream())
        {
            PdfWriter.GetInstance(pdfDoc, ObjememoryStream);
            pdfDoc.Open();
            htmlworker.Parse(sr);
            pdfDoc.Close();
            byte[] Filebytes = ObjememoryStream.ToArray();
            ObjememoryStream.Close();

            using (MemoryStream inputData = new MemoryStream(Filebytes))
            {
                using (MemoryStream outputData = new MemoryStream())
                {
                    string PDFFileword = "vithal@C#cornerDemo"; // you can also generate Dynamic word
                    PdfReader reader = new PdfReader(inputData);
                    PdfEncryptor.Encrypt(reader, outputData, true, PDFFileword, PDFFileword, PdfWriter.ALLOW_SCREENREADERS);
                    Filebytes = outputData.ToArray();
                    Response.ContentType = "application/pdf";
                    Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf");
                    Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    Response.BinaryWrite(Filebytes);
                    Response.End();
                    GridView1.AllowPaging = true;
                    GridView1.DataBind();
                }
            }
        }
    }
}

Now run the application and click on the Export Button. The following popup is shown.

Export Button

Now click on the open with option. It will then prompt you to enter a word as.

Prompt

Now enter an incorrect word and it will show the following message.

Message

Now enter the correct word as vithal@C#cornerDemo, and then the file will be opened with the following records.

Record

Note

  • Download the Zip file from the attachment for the full source code of an application.
  • Change the connection string from the web. config file as per your server location.
  • You can also send this file through an email as an attachment on the Export button click by creating an email method.

Summary

I hope this article is useful for all readers, if you have any suggestion then please contact me including beginners also.


Similar Articles