I'm trying to protect PDF file with permissions and passwords and then save it with "saveIncremental" method (because if signature is inside PDF file I want it to remain valid even after protection).
Here is code snippet:
StandardProtectionPolicy standardProtectionPolicy = new StandardProtectionPolicy(ownerPassword, userPassword, accessPermission);
File protectedFile = new File(pdfFile.getParent(), substring + "_protected.pdf");
try (PDDocument document = PDDocument.load(pdfFile)) {
document.protect(standardProtectionPolicy);
SecurityHandler securityHandler = document.getEncryption().getSecurityHandler();
if (!securityHandler.hasProtectionPolicy()) {
throw new IllegalStateException("PDF contains an encryption dictionary, please remove it with "
+ "setAllSecurityToBeRemoved() or set a protection policy with protect()");
}
securityHandler.prepareDocumentForEncryption(document);
// update and save
document.getDocument().getEncryptionDictionary().setNeedToBeUpdated(true);
document.getEncryption().getCOSDictionary().setNeedToBeUpdated(true);
COSDictionary encrypt = (COSDictionary) document.getDocumentCatalog().getCOSObject().getDictionaryObject(COSName.ENCRYPT);
if (encrypt != null) encrypt.setNeedToBeUpdated(true);
document.getDocumentCatalog().getPages().getCOSObject().setNeedToBeUpdated(true);
document.getDocumentCatalog().getCOSObject().setNeedToBeUpdated(true);
document.saveIncremental(new FileOutputStream(protectedFile));
}
I used this file.
Here are results - protected PDF file and same file after "allSecurityToBeRemoved".
User password is "user", owner password is "owner".
Problem is that protected file. Its content cannot be seen and signature is invalid and all signature info is showed in unreadable chars...
With "save" it works but with "saveIncremental" not. Is it possible to make it work with "saveIncremental" so signature remains valid? If yes, how?
I'm using PDFBox 2.0.7 and Adobe Acrobat Reader DC.
Thanks for all help!