How to protect an already existing PDF with a pass

2020-03-30 05:18发布

问题:

How to set password for an existing PDF?

回答1:

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?



回答2:

Answer for @Alberto Question: How do u encrypt a pdf if only you have the byte array as input - and need another byte array as output, Used the previous answer.

I have a method called addPassword(byte[] templateByte) which accepts byte array of PDF file as a parameter and returns the encrypted byte array as a response.

public byte[] addPassword(byte[] templateByte)
    {

        String USER_PASS = "Hello123";
        String OWNER_PASS = "Deva123";
        PdfReader pdfReader = null;

        ByteArrayOutputStream byteArrayOutputStream = ByteArrayOutputStream(templateByte.length);

        byteArrayOutputStream.write(templateByte, 0, templateByte.length); 

        try
        {

            pdfReader = new PdfReader(templateByte);
            PdfStamper stamper = new PdfStamper(pdfReader, byteArrayOutputStream);
            stamper.setEncryption(USER_PASS.getBytes(), OWNER_PASS.getBytes(),
                    PdfWriter.ALLOW_PRINTING,
                    PdfWriter.ENCRYPTION_AES_128 | PdfWriter.DO_NOT_ENCRYPT_METADATA);
            stamper.close();
            pdfReader.close();

            return byteArrayOutputStream.toByteArray();

        }
        catch (Exception e)
        {

            e.printStackTrace();
        }

        return byteArrayOutputStream.toByteArray();
    }


标签: java itext