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:

  1. using iTextSharp.text;  
  2. using iTextSharp.text.pdf;  
  3. 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):
 
 
 
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#" - "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. Adda 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 details how to bind a Grid View from the database then refer to the following article of mne.

Now, for this article create the following function in the default.aspx.cs page to bind the Grid View:
  1. private void Bindgrid()    
  2.   {    
  3.       connection();    
  4.       query = "select *from Employee";//not recommended this i have written just for example,write stored procedure for security    
  5.       com = new SqlCommand(query, con);    
  6.       SqlDataReader dr = com.ExecuteReader();    
  7.       GridView1.DataSource = dr;    
  8.       GridView1.DataBind();    
  9.       con.Close();    
  10.     
  11.   }  
Now, call the preceding function on page load as:
  1. protected void Page_Load(object sender, EventArgs e)  
  2.    {  
  3.        if (!IsPostBack)  
  4.        {  
  5.            Bindgrid();  
  6.   
  7.        }  
  8.    } 
 
Now run the application, then we can see the following records in the Grid View as:
 
 
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 occurrs, such as "GridView' must be placed inside a form tag with runat=server."
  1. public override void VerifyRenderingInServerForm(Control control)    
  2.  {    
  3.      //required to avoid the runtime error "    
  4.      //Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server."    
  5.  }   
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:
 
 
 
Now create the following function to export the Grid View to word-protect the PDF as:
  1. private void wordProtectedPDF()  
  2.  {  
  3.   
  4.      StringWriter sw = new StringWriter();  
  5.      HtmlTextWriter hw = new HtmlTextWriter(sw);  
  6.      GridView1.RenderControl(hw);  
  7.      StringReader sr = new StringReader(sw.ToString());  
  8.   
  9.      Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);  
  10.      HTMLWorker htmlworker = new HTMLWorker(pdfDoc);  
  11.   
  12.      using (MemoryStream ObjememoryStream = new MemoryStream())  
  13.      {  
  14.          PdfWriter.GetInstance(pdfDoc, ObjememoryStream);  
  15.          pdfDoc.Open();  
  16.          htmlworker.Parse(sr);  
  17.          pdfDoc.Close();  
  18.          byte[] Filebytes = ObjememoryStream.ToArray();  
  19.          ObjememoryStream.Close();  
  20.          using (MemoryStream inputData = new MemoryStream(Filebytes))  
  21.          {  
  22.              using (MemoryStream outputData = new MemoryStream())  
  23.              {  
  24.                  string PDFFileword = "vithal@C#cornerDemo";//you can also generate Dynamic word  
  25.                  PdfReader reader = new PdfReader(inputData);  
  26.                  PdfEncryptor.Encrypt(reader, outputData, true, PDFFileword, PDFFileword, PdfWriter.ALLOW_SCREENREADERS);  
  27.                  Filebytes = outputData.ToArray();  
  28.                  Response.ContentType = "application/pdf";  
  29.                  Response.AddHeader("content-disposition""attachment;filename=GridViewExport.pdf");  
  30.                  Response.Cache.SetCacheability(HttpCacheability.NoCache);  
  31.                  Response.BinaryWrite(Filebytes);  
  32.                  Response.End();  
  33.                  GridView1.AllowPaging = true;  
  34.                  GridView1.DataBind();  
  35.              }  
  36.          }  
  37.      }  
  38.   
  39.  } 
Now call above method on export button click as
  1. protected void Button1_Click(object sender, EventArgs e)  
  2.    {  
  3.        //calling method to generate word Protected PDF  
  4.        wordProtectedPDF();  
  5.    } 
 Now the entire code of the Default.aspx.cs page will be as follows:
  1. using System;  
  2. using System.Web.UI;  
  3. using System.Configuration;  
  4. using System.Data.SqlClient;  
  5. using System.IO;  
  6. using System.Web;  
  7. using iTextSharp.text;  
  8. using iTextSharp.text.pdf;  
  9. using iTextSharp.text.html.simpleparser;  
  10.   
  11. public partial class _Default : System.Web.UI.Page  
  12. {  
  13.     private SqlConnection con;  
  14.     private SqlCommand com;  
  15.     private string constr, query;  
  16.     private void connection()  
  17.     {  
  18.         constr = ConfigurationManager.ConnectionStrings["getconn"].ToString();  
  19.         con = new SqlConnection(constr);  
  20.         con.Open();  
  21.   
  22.     }  
  23.     protected void Page_Load(object sender, EventArgs e)  
  24.     {  
  25.         if (!IsPostBack)  
  26.         {  
  27.             Bindgrid();  
  28.   
  29.         }  
  30.     }  
  31.   
  32.     public override void VerifyRenderingInServerForm(Control control)  
  33.     {  
  34.         //required to avoid the runtime error "  
  35.         //Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server."  
  36.     }  
  37.   
  38.     private void Bindgrid()  
  39.     {  
  40.         connection();  
  41.         query = "select *from Employee";//not recommended this i have written just for example,write stored procedure for security  
  42.         com = new SqlCommand(query, con);  
  43.         SqlDataReader dr = com.ExecuteReader();  
  44.         GridView1.DataSource = dr;  
  45.         GridView1.DataBind();  
  46.         con.Close();  
  47.   
  48.     }  
  49.     protected void Button1_Click(object sender, EventArgs e)  
  50.     {  
  51.         //calling method to generate word Protected PDF  
  52.         wordProtectedPDF();  
  53.     }  
  54.     private void wordProtectedPDF()  
  55.     {  
  56.   
  57.   
  58.         StringWriter sw = new StringWriter();  
  59.         HtmlTextWriter hw = new HtmlTextWriter(sw);  
  60.         GridView1.RenderControl(hw);  
  61.         StringReader sr = new StringReader(sw.ToString());  
  62.   
  63.         Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);  
  64.         HTMLWorker htmlworker = new HTMLWorker(pdfDoc);  
  65.   
  66.         using (MemoryStream ObjememoryStream = new MemoryStream())  
  67.         {  
  68.             PdfWriter.GetInstance(pdfDoc, ObjememoryStream);  
  69.             pdfDoc.Open();  
  70.             htmlworker.Parse(sr);  
  71.             pdfDoc.Close();  
  72.             byte[] Filebytes = ObjememoryStream.ToArray();  
  73.             ObjememoryStream.Close();  
  74.             using (MemoryStream inputData = new MemoryStream(Filebytes))  
  75.             {  
  76.                 using (MemoryStream outputData = new MemoryStream())  
  77.                 {  
  78.                     string PDFFileword = "vithal@C#cornerDemo";//you can also generate Dynamic word  
  79.                     PdfReader reader = new PdfReader(inputData);  
  80.                     PdfEncryptor.Encrypt(reader, outputData, true, PDFFileword, PDFFileword, PdfWriter.ALLOW_SCREENREADERS);  
  81.                     Filebytes = outputData.ToArray();  
  82.                     Response.ContentType = "application/pdf";  
  83.                     Response.AddHeader("content-disposition""attachment;filename=GridViewExport.pdf");  
  84.                     Response.Cache.SetCacheability(HttpCacheability.NoCache);  
  85.                     Response.BinaryWrite(Filebytes);  
  86.                     Response.End();  
  87.                     GridView1.AllowPaging = true;  
  88.                     GridView1.DataBind();  
  89.                 }  
  90.             }  
  91.         }  
  92.   
  93.     }  

 Now run the application and click on the Export Button. The following popup is shown:
 
 
Now click on open with option. It will then prompt you to enter a word as:
 
 
 
Now enter an incorrect word and it will show the following message:
 
 
Now enter a correct word as vithal@C#cornerDemo, then the file will be opened with the following records:
 
 
 
Note
  • Download the Zip file from the attachment for the full source code of an application.
  • Change 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.
 

Up Next
    Ebook Download
    View all
    Learn
    View all