How to protect an already existing PDF with a password?

后端 未结 2 1096
有刺的猬
有刺的猬 2021-01-15 17:57

How to set password for an existing PDF?

2条回答
  •  长情又很酷
    2021-01-15 18:41

    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();
        }
    

提交回复
热议问题