Add password security to PDF and restrict user privileges

Security, Manipulate PDF
11/2/2011

Downloads

The following code sample shows how to add security settings to a PDF document. These security settings include a password, AES 256 bit encryption and the restriction of user privileges.

C# code sample

1 using ( FileStream inFile = new FileStream( @"..\..\..\inputDocuments\PackingLightBrochure.pdf", FileMode.Open, FileAccess.Read ) ) 2 { 3 // open the source document 4 Document document = new Document( inFile ); 5 6 // add new security settings 7 PasswordSecurity passwordSecurity = new PasswordSecurity(); 8 document.Security = passwordSecurity; 9 passwordSecurity.UserPassword = "user"; 10 passwordSecurity.OwnerPassword = "owner"; 11 passwordSecurity.EncryptionLevel = EncryptionLevel.AES_256bit; //NOTICE: for AES_256bit Acrobat 9 (or higher) is required to view!!! 12 passwordSecurity.Print = false; // disable print privilege for users 13 passwordSecurity.CopyExtract = false; // disable copy privilege for user 14 15 // write the modified document to disk 16 using ( FileStream outFile = new FileStream( @"..\..\addsecuritysettings.pdf", FileMode.Create, FileAccess.Write ) ) 17 { 18 document.Write( outFile ); 19 } 20 }

VB.NET code sample

1 Using inFile As New FileStream("..\..\..\inputDocuments\PackingLightBrochure.pdf", FileMode.Open, FileAccess.Read) 2 ' open the source document 3 Dim document As New Document(inFile) 4 5 ' add new security settings 6 Dim passwordSecurity As New PasswordSecurity() 7 document.Security = passwordSecurity 8 passwordSecurity.UserPassword = "user" 9 passwordSecurity.OwnerPassword = "owner" 10 passwordSecurity.EncryptionLevel = EncryptionLevel.AES_256bit 11 'NOTICE: for AES_256bit Acrobat 9 (or higher) is required to view!!! 12 passwordSecurity.Print = False 13 ' disable print privilege 14 passwordSecurity.CopyExtract = False 15 ' disable copy privilege 16 ' write the modified document to disk 17 Using outFile As New FileStream("..\..\addsecuritysettings.pdf", FileMode.Create, FileAccess.Write) 18 document.Write(outFile) 19 End Using 20 End Using

When the user tries to open the document, the following pop-up is shown:

add-security-settings-pdf.png