Encrypt PDF File
Contents
[
Hide
]
Encrypt PDF file
Use PdfFileSecurity when you need to protect a PDF with passwords and privilege rules.
Steps
- Create a
PdfFileSecurityinstance. - Bind the source PDF with
bindPdf. - Build a
DocumentPrivilegeobject that matches the allowed actions. - Call the appropriate
encryptFileoverload for the key size and algorithm you need. - Save the secured file and close the object.
Java examples
public static void encryptPdfWithUserOwnerPassword(Path inputFile, Path outputFile) {
PdfFileSecurity fileSecurity = new PdfFileSecurity();
fileSecurity.bindPdf(inputFile.toString());
DocumentPrivilege privilege = DocumentPrivilege.getForbidAll();
privilege.setAllowPrint(true);
fileSecurity.encryptFile("user_password", "owner_password", privilege, KeySize.x128);
fileSecurity.save(outputFile.toString());
fileSecurity.close();
}
public static void encryptPdfWithPermissions(Path inputFile, Path outputFile) {
PdfFileSecurity fileSecurity = new PdfFileSecurity();
fileSecurity.bindPdf(inputFile.toString());
DocumentPrivilege privilege = DocumentPrivilege.getAllowAll();
privilege.setAllowPrint(false);
privilege.setAllowCopy(false);
fileSecurity.encryptFile("user_password", "owner_password", privilege, KeySize.x128);
fileSecurity.save(outputFile.toString());
fileSecurity.close();
}
public static void encryptPdfWithEncryptionAlgorithm(Path inputFile, Path outputFile) {
PdfFileSecurity fileSecurity = new PdfFileSecurity();
fileSecurity.bindPdf(inputFile.toString());
DocumentPrivilege privilege = DocumentPrivilege.getForbidAll();
privilege.setAllowPrint(true);
fileSecurity.encryptFile("user_password", "owner_password", privilege, KeySize.x256, Algorithm.AES);
fileSecurity.save(outputFile.toString());
fileSecurity.close();
}