Naveen's Weblog

Bridge to future

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


4 Responses to “Apply password to existing PDF file”

  1. 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.

  2. Jerry said

    Good tip.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: