Generate Random Password for PDF with asp.net

In the previous article we discussed about Dynamic PDF generation with static password.Now Lets try with some random password that means generate a password at the time of pdf creation to provide more secuirty for the pdf file.
Previous article :

Create Password protected PDF using iTextsharp
First ,Drag one label from toolbox and change properties as
Name =" "(Empty)
Id=lblPassword
Visible=false;
Now, write a method to generate a random password with the combination of string and number
private string setpassword()
{
StringBuilder SB = new StringBuilder();
SB.Append(RandomString(3, true));
SB.Append(RandomNumber(100, 999));
return SB.ToString();
}
The following method return a random number
private int RandomNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}
The following method return a random string
StringBuilder SB = new StringBuilder();
Random random = new Random();
char ch ;
for(int i=0; i lessthan size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))) ;
SB.Append(ch);
}
if(lowerCase)
return SB.ToString().ToLower();
return SB.ToString();
Now write the following method to generate a PDF file
First get the generated password in to label,Write the following code inside the button event
protected void btnCreatePDF_Click(object sender, EventArgs e)
{
lblPassword.Text=setpassword();
}
Following is the complete code to generate pdf file with random password
protected void btnCreatePDF_Click(object sender, EventArgs e)
{
lblPassword.Text=setpassword();
string path = Server.MapPath("~/");
string fileName =txtPDFName.Text + ".pdf";
string MFileName = string.Empty;
object TargetFile = path + fileName;
iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(TargetFile.ToString());
MFileName = TargetFile.ToString();
MFileName = MFileName.Insert(ModifiedFileName.Length - 4, "R2T4");
lblpassword.Text=Setpassword();
iTextSharp.text.pdf.PdfEncryptor.Encrypt(reader, new FileStream(MFileName, FileMode.Append), iTextSharp.text.pdf.PdfWriter.STRENGTH128BITS, lblpassword.Text, "", iTextSharp.text.pdf.PdfWriter.AllowPrinting);
if (File.Exists(TargetFile.ToString()))
File.Delete(TargetFile.ToString());
}
Previous article :
I Hope this will helps somebody..Happy Coding....
Labels: .Net Tutorials, Aspnet, C#

1 Comments:
This comment has been removed by a blog administrator.
Post a Comment
Subscribe to Post Comments [Atom]
<< Home