Encrypting a File

PDF encryption requires two passwords: the "user password" to open and view the file with restricted permissions, the "owner password" to access the file with all permission.

Load and Save Encrypted

This small sample shows how to encrypt a file so that it can be viewed, but not printed.

PDDocument doc = PDDocument.load(new File("filename.pdf"));

// Define the length of the encryption key.
// Possible values are 40, 128 or 256.
int keyLength = 256;

AccessPermission ap = new AccessPermission();

// disable printing,
ap.setCanPrint(false);
//disable copying
ap.setCanExtractContent(false);
//Disable other things if needed...

// Owner password (to open the file with all permissions) is "12345"
// User password (to open the file but with restricted permissions, is empty here)
StandardProtectionPolicy spp = new StandardProtectionPolicy("12345", "", ap);
spp.setEncryptionKeyLength(keyLength);

//Apply protection
doc.protect(spp);

doc.save("filename-encrypted.pdf");
doc.close();