How to Protect PDF with Password using iText in Java?

In my previous article I have explained about how to create PDF document using iText with simple example. This tutorial explains how to add a password protection for your PDF document. iText doesn’t provide the password feature in its own API, however it internally uses another third part implementation and implements the password protection.

iText internally uses the library bouncycastle to generate the password PDF file. You have to download the JAR file from the given link before run the below example. Once the PDF is created, you will be asked for the password when open the document. pdfWriter.setEncryption is taking the bytes array as the arguments, so you need to convert your inputs to bytes and pass it.



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

public class PDFConversionDemo {
	    public static void main(String[] args) {
	        try {
	            OutputStream file = new FileOutputStream(new File("SamplePDF.pdf"));
	            Document document = new Document();
	            PdfWriter pdfWriter = PdfWriter.getInstance(document, file);
	            pdfWriter.setEncryption("krishna".getBytes(), "testpass".getBytes(),
	                    PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128);
	            document.add(new Paragraph("First iText PDF"));

	        } catch (Exception e) {




Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Share This

Share this post with your friends!