iText is very powerful library. It is used extensively to create PDF files in Java applications. Although not free, iText is the de-fecto Java library for working with PDF files. It has been extensively used in different Java related products for generating and manipulating PDF files.
Let us see how iText can be used to set password protection (encryption) to a PDF file. Also how to read an encrypted PDF file in Java.
For this we are using our Generate PDF in Java using iText tutorial. You might want to have a look into that tutorial to have an overview of iText and its different APIs that can be used for PDF generation.
To set encryption in iText following API can be used.
Thus .setEncryption() method sets password protection to any PDF file.
Before we get started with code, we need few JAR files. iText internally uses bouncycastle.org library to encrypt the PDF files. We will need following JAR files in addition to iText JAR.
You can download all these JARs along with the demo source code at the end of this tutorial.
Now following is the Java code to Generate a PDF file and set Password protection to it.
Thus we used the same steps to generate PDF file that we used in previous tutorial. Just added one line writer.setEncryption() to set password to generated PDF.
Note that in setEncryption() method, we passes several arguments. First two parameters are the password values in bytes. We passed Hello123 and Owner123 as password values. Also the next argument is permission you want to give to user. Following are several permission values.
You can provide multiple permissions by ORing different values. For example PdfWriter.ALLOW_PRINTING | PdfWriter.ALLOW_COPY.
The last parameter is the type of encryption you want to use to encrypt PDF. Following are several allowed values.