Saturday, 18 April 2015

how to set password for pdf in asp.net


In this article I will explain how to set password for pdf in asp.net.

I am creating a database table in Sql server
USE [chinnu]
GO

/****** Object: Table [dbo].[EmployeeInfo] Script Date: 10/31/2013 22:39:45 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[EmployeeInfo](
[EmpId] [nvarchar](50) NOT NULL,
[EmpName] [nvarchar](50) NOT NULL,
[EmpAddress] [nvarchar](50) NOT NULL,
[EmpDesignation] [nvarchar](50) NOT NULL
) ON [PRIMARY]

GO

I am created an empty solution with name PdfPassword
Now I am adding a webform PdfLock.aspx.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="PdfLock.aspx.cs"Inherits="PdfPassword.PdfLock" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gridview" runat="server" AutoGenerateColumns="False" >
<Columns>
<asp:BoundField DataField="EmpId" HeaderText="EmployeeId" InsertVisible="False"
/>
<asp:BoundField DataField="EmpName" HeaderText="EmployeeName" InsertVisible="False"
/>
<asp:BoundField DataField="EmpAddress" HeaderText="EmployeeAddress" />
<asp:BoundField DataField="EmpDesignation" HeaderText="EmployeeDesignation" />
</Columns>
</asp:GridView>
<asp:ImageButton ID="ImageButton1" runat = "server" ImageUrl ="~/pdflock.png" ToolTip ="Click to get PDF Format" Width = "100" Height = "70"
onclick="btnPDF_Click
" />
</div>
</form>
</body>
</html>

Now I am writing the logic in aspx.cs
Add iTextSharp Dll.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.IO;
using System.Configuration;
using System.Data;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;

namespace PdfPassword
{
public partial class PdfLock : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

if (!IsPostBack)
{
BindGridData();

}
}
private void BindGridData()
{
try
{
using (SqlConnection con = newSqlConnection(ConfigurationManager.ConnectionStrings["Connstring"].ConnectionString))
{
SqlCommand command = new SqlCommand("SELECT * from EmployeeInfo", con);
SqlDataAdapter da = new SqlDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
gridview.DataSource = dt;
gridview.DataBind();
}
}
catch (Exception ex)
{
}

}

protected void btnPDF_Click(object sender, ImageClickEventArgs e)
{


StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
HtmlForm hfrm = new HtmlForm();
gridview.Parent.Controls.Add(hfrm);
hfrm.Attributes["runat"] = "server";
hfrm.Controls.Add(gridview);
hfrm.RenderControl(htw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
MemoryStream ms = new MemoryStream();
PdfWriter.GetInstance(pdfDoc, ms);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
byte[] bytes = ms.ToArray();
ms.Close();
MemoryStream input = new MemoryStream(bytes);
MemoryStream output = new MemoryStream();
string password = "password123";
PdfReader pr = new PdfReader(input);
PdfEncryptor.Encrypt(pr, output, true, password, password,PdfWriter.ALLOW_SCREENREADERS);
bytes = output.ToArray();
Response.AddHeader("content-disposition","attachment;filename=EmployeeInformation.pdf");
Response.ContentType = "application/pdf";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(bytes);
Response.End();
}

public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}

}
}

After completing the Steps Press F5.
We can see the Out Put.


No comments:

Post a Comment