Skip to main content
Version: 1.3

Encrypt and decrypt a PDF document

The Pdftools SDK provides methods to open and save encrypted PDF documents. The PDF encryption process applies encryption to all streams (e.g. images) and text, but not to other items in the PDF document. This means the structure of the PDF document is accessible, but the content of its pages is encrypted.

Opening an encrypted PDF document

Quick start

Download the full sample now in C# and Java.

Interested in C or other language samples? Let us know on the contact page and we'll add it to our samples backlog.

To open an encrypted PDF document, a password must be provided. Up to two passwords can be specified for a document: an 'Owner' password and a 'User' password. Permissions for a document depends on the type of password provided. See Permissions and passwords in PDF documents.

In the Pdftools SDK, the password is provided as an optional parameter to the static Document.Open method.

// Open an encrypted input document
// The password parameter is optional, and only required to open an encrypted PDF document
using var inStr = File.OpenRead(inPath);
using var inDoc = Document.Open(inStr, password);

If the PDF document is encrypted and the password parameter is not provided or is not valid, the Document.Open method fails with a PasswordException.

Saving an encrypted PDF document

Quick start

Download the full sample now in C# and Java.

Interested in C or other language samples? Let us know on the contact page and we'll add it to our samples backlog.

With the Pdftools SDK, you can open and read encrypted PDF files using the standard security handler. You can encrypt output PDF documents, adding an owner password, a user password, or both.

This example shows how encryption is applied to the output document during the PDF optimization process. You can also apply encryption during other processes where OutputOptions are used, e.g. signing.

// Create output stream
using var outStr = File.Create(outPath);

// Create output options and specify encryption parameters
// In this example, a 'User' is only granted permission to fill forms and print the document
var outOpt = new OutputOptions();
var outEnc = new Encryption(strUserPassword, strOwnerPassword, (Permission.FillForms | Permission.Print));
outOpt.Encryption = outEnc;

// Optimize the input PDF document and save it to a file, applying the specified output encryption
using var outDoc = optimizer.OptimizeDocument(inDoc, outStr, profile, outOpt);

Removing encryption from an encrypted PDF document

Removing encryption from an encrypted document is as simple as the process for encrypting the document. After you have opened the encrypted document as shown above, the document can be processed in the same way as for encryption, but setting the Encryption to null.

// Create output options and remove encryption by setting it to null
var outOpt = new OutputOptions();
outOpt.Encryption = null;