I am creating an encrypted PDF using this code:
Document document = new Document(
new Rectangle(PageSize.A4.getWidth(), PageSize.A4.getHeight()));
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream(RESULT1));
writer.setBoxSize("art", new Rectangle(36, 54, 555, 791));
writer.setEncryption("Vibhu".getBytes(), "Vibhu@123456789".getBytes(),
PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128);
document.open();
// Creating Tables and Cells
document.close();
I omitted to code that creates cells and tables and the code that creates a form in which values such as firstname, lastname can be entered.
Then I manipulate the form like this.
private void manipulatePdf(String src, String dest, EclaimsVO eclaimsVO,
String language) throws IOException, DocumentException {
File file = new File(src);
if (isObjectPresent(file)) {
PdfReader reader = new PdfReader(src);
PdfStamper stamper;
stamper = new PdfStamper(reader, new FileOutputStream(dest),
'\0', false);
form = stamper.getAcroFields();
addToForm("field_2", eclaimsVO.getName());
addToForm("field_3", eclaimsVO.getSurName());
stamper.close();
}
}
I have been trying to add a password to a PDF file by setEncryption()
when I create the file, but it throws this exception when I read the file:
com.itextpdf.text.exceptions.BadPasswordException: Bad user password
at com.itextpdf.text.pdf.PdfReader.readPdf(PdfReader.java:681)
at com.itextpdf.text.pdf.PdfReader.<init>(PdfReader.java:181)
at com.itextpdf.text.pdf.PdfReader.<init>(PdfReader.java:219)
at com.itextpdf.text.pdf.PdfReader.<init>(PdfReader.java:207)
at com.itextpdf.text.pdf.PdfReader.<init>(PdfReader.java:197)
But, if I change the unethicalreading to true and set the OWNER-PASSWORD as an empty string the exception doesn't come up.
writer.setEncryption("".getBytes(), "Vibhu@123456789".getBytes(),
PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128);
PdfReader.unethicalreading = true;
And now when I try opening the PDF it gets opened without a password prompt. But the document has a "Sample.pdf(SECURED)" title when I open the PDF.