Table of Contents
PDF File Encryption

Overview

EO.Pdf can read or write encrypted PDF files. This section contains general information about passwords for PDF file as well as how to read and write encrypted PDF files with EO.Pdf.

PDF File Passwords

Reading Encrypted PDF Files

Writing Encrypted PDF Files

PDF File Passwords

A PDF file can be encrypted by up to two passwords: an owner password and a user password. The following guidelines apply when using these two passwords:

  • To allow everyone to open the PDF file, but restrict certain permissions on the file (such as disallow printing), set the owner password;
  • To require a password to open the PDF file, set both the owner password and the user password;
  • When both passwords are set, the file can be opened with either password;

Reading Encrypted PDF Files

To read an encrypted PDF file with a password, you can create a PdfDocumentSecurity object with the password and then pass this object to PdfDocument's constructor. For example:

//Create a PdfDocumentSecurity object with password "1234",
//this can either be the owner password or the user password
PdfDocumentSecurity security = new PdfDocumeentSecurity("1234");
        
//Load the PDF file with the given password
PdfDocument doc = new PdfDocument(pdfFileName, security);

Or use a simplified version:

//Load the PDF file with the given password
PdfDocument doc = new PdfDocument(pdfFileName, "1234");

The second version internally creates a PdfDocumentSecurity object with the given password and then invoke the first version.

Once the file is loaded, it is fully decrypted. You can save it again as encrypted or unencrypted. If the provided password is wrong, then an exception will be thrown.

Writing Encrypted PDF Files

A PDF file is saved as encrypted when one of the following conditions is true:

If you wish to protect your file from being opened without a password, then you should set both OwnerPassword and UserPassword. For example:

//Create a PDF file with user password set to "1234" and owner
//password set to "5678". PDF Viewer will prompt user to enter 
//a password before opening this file. Either password will
//gain access to the file
doc.Security.UserPassword = "1234";
doc.Security.OwnerPassword = "5678";
doc.Save(fileName);

If you wish everyone to be able to open the file without a password, but wish to disallow certain permissions, then you can modify Permissions property, for example:

//This is the same as clearing PdfDocumentPermission.Printing
//flag from doc.Security.Permissions
doc.Security.Disallow(PdfDocumentPermission.Printing);        

//This step is optional. If you set this password, then PDF
//authoring software (such as Adobe Acrobat) will require this
//password if you wish to change the file permissions. Having
//this password or not does not affect Adobe Reader's behavior
doc.Security.OwnerPassword = "1234";

//Save the file as encrypted
doc.Save(fileName);