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

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*

Close
Please support the site
By clicking any of these buttons you help our site to get better