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.

package javabeat.net.pdf;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

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.open();
	            document.add(new Paragraph("First iText PDF"));
	            document.close();
	            file.close();

	        } catch (Exception e) {

	            e.printStackTrace();
	        }
	    }

}

itext-pdf-password
itext-pds-password-doc

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Pin It on Pinterest

Share This

Share this post with your friends!

Share This

Share this post with your friends!