How to protect an already existing PDF with a password?

How to set password for an existing PDF? Posted on StackOverflow on Dec 2, 2014 by Sreekanth P It's as simple as this: PdfReader reader = new PdfReader(src); WriterProperties props = new

How to set password for an existing PDF?

Posted on StackOverflow on Dec 2, 2014 by Sreekanth P

It's as simple as this:

PdfReader reader = new PdfReader(src);
WriterProperties props = new WriterProperties()
        .setStandardEncryption(USERPASS, OWNERPASS, EncryptionConstants.ALLOW_PRINTING,
                EncryptionConstants.ENCRYPTION_AES_128 | EncryptionConstants.DO_NOT_ENCRYPT_METADATA);
PdfWriter writer = new PdfWriter(new FileOutputStream(dest), props);
PdfDocument pdfDoc = new PdfDocument(reader, writer);
pdfDoc.close();

Note that USERPASS and OWNERPASS are of type byte[]: public static byte[] USERPASS = "superuser".getBytes(); public static byte[] OWNERPASS = "superowner".getBytes();

You have different options for the permissions (look for EncryprionConstants starting with ALLOW_) and also you can chose from different encryption algorithms.

Click this link if you want to see how to answer this question in iText 5.


Share this article

Ready to use iText?

Try our iText 7 Library and add-ons FREE for 30 days. Test your proof of concept, and see if our solution is right for you.

Get my FREE trial
Contact

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now