How to set password for an existing PDF?
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();
}