Search code examples
javaitext

How to protect an already existing PDF with a password?


How to set password for an existing PDF?


Solution

  • Did you look at the EncryptionPdf example in chapter 12 of my book?

    It's as simple as this:

    public void encryptPdf(String src, String dest) throws IOException, DocumentException {
        PdfReader reader = new PdfReader(src);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
        stamper.setEncryption(USER, OWNER,
            PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128 | PdfWriter.DO_NOT_ENCRYPT_METADATA);
        stamper.close();
        reader.close();
    }
    

    Note that USER and OWNER are of type byte[]. You have different options for the permissions (look for constants starting with ALLOW_) and you can choose from different encryption algorithms.

    As for the parameters: src is the path to the existing PDF. dest is the path of the encrypted PDF. It should be obvious that you can not write to a file while you are reading it. That is explained here: How to update a PDF without creating a new PDF?