iText API- Protect PDF Document with Password in Java

In this Java tutorial, we are going to show how you will protect your pdf document with a password using iText API. PdfWriter.setEncryption() method is used to encrypt the PDF document while creating it. We need to pass the arguments in the method while creating new documents.


public void setEncryption(byte[] userPassword, byte[] ownerPassword, int permissions, int encryptionType)

Sets the encryption options for this document. The userPassword and the ownerPassword can be null or have zero length. In this case, the ownerPassword is replaced by a random string. The open permissions for the document can be AllowPrinting, AllowModifyContents, AllowCopy, AllowModifyAnnotations, AllowFillIn, AllowScreenReaders, AllowAssembly and AllowDegradedPrinting.


userPassword – the user password. Can be null or empty.

ownerPassword – the owner password. Can be null or empty.

permissions – the user permissions.

encryptionType – can be any of the following:

  • PdfWriter#ENCRYPTION_AES_128
  • PdfWriter#ENCRYPTION_AES_256

Throws:  DocumentException – if the document is already open

JAR Dependencies

To resolve the JAR dependencies, add following in your pom.xml


You can provide multiple permissions by ORing different values. For example


Check the Full Example
package org.websparrow.itext;


import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

public class ProtectPdfDocument {
	private static String USER_PASS = "RAM123";
	private static String OWNER_PASS = "GOD999";

	public static void main(String[] args) {
		try {

			Document document = new Document(PageSize.A4, 20, 20, 20, 20);

			PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream("iText/protected-doc.pdf"));
			pdfWriter.setEncryption(USER_PASS.getBytes(), OWNER_PASS.getBytes(), PdfWriter.ALLOW_COPY,

			document.add(new Paragraph("Welcome to"));
			document.add(new Paragraph("Don't worry, your pdf document is protected with password."));


			System.out.println("PDf protected with password.");

		} catch (Exception e) {


Now your generated PDF is password protected. Use the RAM123 to open the document.

Screen 1

iText API- Protect PDF Document with Password in Java

Screen 2

iText API- Protect PDF Document with Password in Java

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.