Naveen's Weblog

Bridge to future

Posts Tagged ‘PDF’

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);

//copy the Intermediate file to source file path            
File.Copy(path, SourcePath, true);

//Delete the Intermediate file            

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 🙂

Naveen Prabhu


Posted in C# | Tagged: , , | 4 Comments »