Apply password to existing PDF file
Posted by codingsense on February 26, 2009
Hi friends,
For applying the password to a PDF file, i m using ITextSharp library.
I was searching for the code to apply password to an existing PDF file, but dint find any method in which PDFStamper or PDFWriter would append password for an existing file. So i have used the way of creating an intermediate file and then deleting it.
private void ApplyPassword(string SourcePath,string UserPassword, string OwnerPassword)
{
//Open the path in reader object
PdfReader reader = new PdfReader(SourcePath);
//Get the file Information of the source file
FileInfo finfo = new FileInfo(SourcePath);
//Create a Intermediate path for applying the password
string path = finfo.DirectoryName + "\" + finfo.Name + "1.pdf";
//Apply the Password
PdfStamper stamper = new PdfStamper(reader, new FileStream(path, FileMode.Create));
stamper.SetEncryption(PdfWriter.STANDARD_ENCRYPTION_128, UserPassword , OwnerPassword,
PdfWriter.AllowCopy | PdfWriter.AllowPrinting);
stamper.Close();
reader.Close();
//copy the Intermediate file to source file path
File.Copy(path, SourcePath, true);
//Delete the Intermediate file
File.Delete(path);
}
If anybody know how to give password to a PDF file without creating a intermediate file then i will be pleased to know.
Happy learing
Thanks,
Naveen Prabhu
JP said
where to paste this code
codingsense said
Hi JP,
You can paste it in your application. Just call this method with required parameters and it will apply the password to your PDF. Its a C# code so you can create a sample console application and try it out.
Jerry said
Good tip.
codingsense said
Thanks Jerry