Change Password of PDF File
Contents
[
Hide
]
Change password of PDF file
Use PdfFileSecurity when you need to rotate credentials on an already secured PDF.
Steps
- Create a
PdfFileSecurityinstance. - Bind the secured PDF with
bindPdf. - Call the appropriate
changePasswordoverload, depending on whether you also want to reset privileges and key size. - Save the updated file and close the security object.
Java examples
public static void changeUserAndOwnerPassword(Path inputFile, Path outputFile) {
PdfFileSecurity fileSecurity = new PdfFileSecurity();
fileSecurity.bindPdf(inputFile.toString());
fileSecurity.changePassword("owner_password", "new_user_password", "new_owner_password");
fileSecurity.save(outputFile.toString());
fileSecurity.close();
}
public static void changePasswordAndResetSecurity(Path inputFile, Path outputFile) {
PdfFileSecurity fileSecurity = new PdfFileSecurity();
fileSecurity.bindPdf(inputFile.toString());
DocumentPrivilege privilege = DocumentPrivilege.getForbidAll();
privilege.setAllowPrint(true);
fileSecurity.changePassword("owner_password", "new_user_password", "new_owner_password", privilege, KeySize.x128);
fileSecurity.save(outputFile.toString());
fileSecurity.close();
}
public static void tryChangePasswordWithoutException(Path inputFile, Path outputFile) {
PdfFileSecurity fileSecurity = new PdfFileSecurity();
fileSecurity.bindPdf(inputFile.toString());
if (fileSecurity.tryChangePassword("owner_password", "new_user_password", "new_owner_password")) {
fileSecurity.save(outputFile.toString());
} else {
System.out.println("Password change failed. Check owner password or document security.");
}
fileSecurity.close();
}