我用Apache PdfBox(v1.8.2)lib解密PDF文檔時遇到問題。加密工作正常,但使用相同密碼解密會引發異常。 (Java 1.6)Apache PDFBox - 無法解密PDF
package com.test;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.encryption.AccessPermission;
import org.apache.pdfbox.pdmodel.encryption.StandardDecryptionMaterial;
import org.apache.pdfbox.pdmodel.encryption.StandardProtectionPolicy;
public class PdfEncDecTest {
static String pdfPath = "G:\\files\\filed5b3.pdf";
public final static String PDF_OWNER_PASSWORD = "cd1j";
public final static String PDF_USER_PASSWORD = "";
public static void main(String[] args) throws Exception {
PDDocument document = PDDocument.load(pdfPath);
AccessPermission ap = new AccessPermission();
ap.setCanPrint(true);
ap.setCanExtractContent(false);
ap.setCanExtractForAccessibility(false);
StandardProtectionPolicy spp = new StandardProtectionPolicy(PDF_OWNER_PASSWORD, PDF_USER_PASSWORD, ap);
document.protect(spp);
document.save(pdfPath+".pdf");
document.close();
PDDocument doc = PDDocument.load(pdfPath+".pdf");
if(doc.isEncrypted()) {
StandardDecryptionMaterial sdm = new StandardDecryptionMaterial(PDF_OWNER_PASSWORD);
doc.openProtection(sdm); // org.apache.pdfbox.exceptions.CryptographyException: Error: The supplied password does not match either the owner or user password in the document.
doc.decrypt(PDF_OWNER_PASSWORD); // the same like above
}
doc.close();
}
}
我不知道什麼是錯的。在版本1.8.7中,我得到了相同的異常。我已經發布了上面的完整代碼。
Exception in thread "main" org.apache.pdfbox.exceptions.CryptographyException: Error: The supplied password does not match either the owner or user password in the document.
at org.apache.pdfbox.pdmodel.encryption.StandardSecurityHandler.prepareForDecryption(StandardSecurityHandler.java:265)
at org.apache.pdfbox.pdmodel.encryption.StandardSecurityHandler.decryptDocument(StandardSecurityHandler.java:156)
at org.apache.pdfbox.pdmodel.PDDocument.openProtection(PDDocument.java:1595)
at org.apache.pdfbox.pdmodel.PDDocument.decrypt(PDDocument.java:942)
at com.test.PdfEncDecTest.main(PdfEncDecTest.java:29)
我已經把樣本項目的GitHub:https://github.com/marioosh-net/pdfbox
請使用當前版本(1.8.7)再試一次。如果它仍然不起作用,請在您的問題中加入例外。 – 2014-10-10 09:08:19
我得到了與1.8.7版本相同的例外... – marioosh 2014-10-10 09:50:23