Encrypt Unprotected PDF with Password using iText in Java


In this tutorial we will learn how to use iText API to add password in PDF and how to encrypt existing PDF to write and read data respectively.  While creating password protected PDF, we need to add user password, owner password, permission and encryption type. To encrypt existing PDF with password, iText provides PdfStamper.setEncryption which accepts same arguments as PdfWriter.setEncryption

* @author mahsin
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;
public class Main {
public static void main(String[] args) throws FileNotFoundException, DocumentException, IOException {
       PdfReader reader = new PdfReader("C:/PasswordNOTGivenPDF.pdf");
       PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("C:/PDFwithPassword.pdf"));
       stamper.setEncryption("password".getBytes(), "owner_password".getBytes(),PdfWriter.ALLOW_COPY, PdfWriter.ENCRYPTION_AES_256);
       System.out.println("Successfully Done");

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s