Download PDF as password protected using ITEXTSHARP in asp.net
Download PDF as password protected using ITEXTSHARP in asp.net
This is cool concept
to protect pdf file with Password. In some cases like bill statement and any confidential documents we
have to maintain security ,so that no one else can view its content.so this
problem can be solved using this pdf password protected method.
Step 1: Design web page using your content
<div>
<div id="pdf" runat="server">
<span style="color:brown"> kandy Here</span><br />
<br />
So have fun!!!!
</div>
<asp:Button ID="btnExport" runat="server" Text="Export To PDF" OnClick = "ExportToPDF" BackColor="YellowGreen" />
</div>
Step 2: Logic on .cs Page
Namespace you have to be imports…
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
protected void ExportToPDF(object sender, EventArgs e)
{
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter hw = new HtmlTextWriter(sw))
{
//To
Export all pages
pdf.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 = "kandy";
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();
}
}
}
}
}
}
Comments
Post a Comment