9
votes

With QPDF, you can simply remove restrictions / encryption from a PDF file like so:

qpdf --decrypt infile outfile

I would like to do the same thing with PDFBox in Java:

PDDocument doc = PDDocument.load(inputFilename);
if (doc.isEncrypted()) {
   // remove the encryption to alter the document
}

I've tried this with StandardDecryptionMaterial, but I have no idea what the owner password is. How does QPDF does this?

Sample document:
https://issues.apache.org/jira/secure/attachment/12514714/in.pdf

1
Depending on the type of encryption of the PDF it is easy to decrypt (how else to display it). It beats the concept of this encryption, though, to allow anyone without some authorisation (owner password) to remove the encryption. If you have encrypted PDF files and don't have the owner password, you are expected to turn to the document owner if you require an unencrypted version. - mkl

1 Answers

21
votes

This is what you'd need to do (inspired from the PDFBox WriteDecodedDoc command line tool):

if (doc.isEncrypted()) {
    try {
        doc.decrypt("");
        doc.setAllSecurityToBeRemoved(true);
    } catch (Exception e) {
        throw new Exception("The document is encrypted and we can't decrypt it.", e);
    }
}

Note: you may have to include the Bouncy Castle JAR.