Generate password protected pdf file dynamically in Asp.net


Description:-

Here we will create Password protected Pdf file Dynamically from Gridview Data. PDF File is very useful to read data and we can see clearly in Pdf file. So we can Generate Pdf File Dynamically and set Password as default when we create dynamically in server. Here is the simple code to achieve this functionality in dot net.

Create Table:-

CREATE TABLE [dbo].[Employee](
      [Number] [int] IDENTITY(1,1) NOT NULL,
      [Name] [varchar](50) NOT NULL,
      [Gender] [varchar](50) NOT NULL,
      [Email] [varchar](50) NOT NULL,
      [MobileNumber] [bigint] NOT NULL,
      [Bdate] [date] NULL,
 CONSTRAINT [PK_Employeee] PRIMARY KEY CLUSTERED
(
      [Number] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
 
Default.aspx:-

<div>
   <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Horizontal" Height="123px" Width="594px">
      <Columns>
         <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="80px">
            <HeaderStyle HorizontalAlign="Left" />
            <ItemStyle Width="80px" VerticalAlign="Middle"></ItemStyle>
         </asp:BoundField>
         <asp:BoundField DataField="Gender" HeaderText="Gender" ItemStyle-Width="80px">
            <HeaderStyle HorizontalAlign="Left" />
            <ItemStyle Width="80px" ></ItemStyle>
         </asp:BoundField>
         <asp:BoundField DataField="Email" HeaderText="Email" ItemStyle-Width="80px">
            <HeaderStyle HorizontalAlign="Left" />
            <ItemStyle Width="80px"></ItemStyle>
         </asp:BoundField>
         <asp:BoundField DataField="MobileNumber" HeaderText="MobileNumber" ItemStyle-Width="60px">
            <HeaderStyle HorizontalAlign="Left" />
            <ItemStyle Width="60px"></ItemStyle>
         </asp:BoundField>
         <asp:BoundField DataField="BDate" HeaderText="BDate" ItemStyle-Width="100px">
            <HeaderStyle HorizontalAlign="Left" />
            <ItemStyle Width="120px"></ItemStyle>
         </asp:BoundField>
      </Columns>
      <FooterStyle BackColor="#CCCC99" ForeColor="Black" />
      <HeaderStyle BackColor="#333333" ForeColor="White" Font-Bold="True"></HeaderStyle>
      <PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
      <SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
      <SortedAscendingCellStyle BackColor="#F7F7F7" />
      <SortedAscendingHeaderStyle BackColor="#4B4B4B" />
      <SortedDescendingCellStyle BackColor="#E5E5E5" />
      <SortedDescendingHeaderStyle BackColor="#242121" />
   </asp:GridView>
   <br />
   <asp:Button ID="btnExport" runat="server" Text="Export To PDF" OnClick="ExportToPDF" />
</div>

Default.aspx.cs:-

Now Go to Code behind and Create Method for Bind Gridview when page load first time in browser. And Call in Page_Load () method.

private void BindGrid()
{
    string strConnString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
    using (SqlConnection con = new SqlConnection(strConnString))
    {
        using (SqlCommand cmd = new SqlCommand("select * FROM Employee"))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    GridView1.DataSource = dt;
                    GridView1.DataBind();
                }
            }
        }
    }
}

Page_load () method when page call first time in browser or else it is not Postback.

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

Now generate ExporttoPdf button click event and code for Generate Password Protected Pdf file.

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 = "Umesh";
            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=" + "Export_" + DateTime.Now.ToShortDateString() + "_" + DateTime.Now.ToString("T") + ".pdf");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.BinaryWrite(bytes);
            Response.End();
          }
        }
      }
    }
  }
}

Here I have Set Password “Umesh” and Name it When Pdf file Export like "Export_Todate.Pdf". When you Run and Export file from Gridview you can see in your Downloaded file.

Now Click on Export to Pdf button and Download Pdf File and Open Pdf file.

Now Enter Password and see Data from that Pdf File.

Related Posts

Previous
Next Post »

Thanks for comments.....