CodesJava

Easy learning with example program codes

How to add password protection to PDF using iText in Java?

The PdfWriter class provides the setEncryption() method to set the password protection on a pdf file.

Syntax:

public void setEncryption(byte[] userPassword, byte[] ownerPassword, int permissions, int encryptionType) throws DocumentException.
1. userPassword – It specify the user password.
2. ownerPassword – It specify the owner password.
3. permissions – It specify the user permissions.
4. encryptionType – It specify the type of encryption.

Note: We can provide multiple permission by ORing them.
e.g. PdfWriter. ALLOW_COPY | PdfWriter.ALLOW_PRINTING

Steps:

1. Create Document instance. It represents the current document to which we are adding content.
2. Create OutputStream instance. It represents the generated pdf.
3. Create PDFWriter instance and pass Document and OutputStream instance to its constructor.
4. Add password protection using setEncryption() method of the PdfWriter class.
5. Open the Document by calling document.open().
6. Add the content to the document by calling document.add() method.
7. Close the document by calling document.close() method.

Example:

PDFPasswordExample.java

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;
 
/**
 * This class is used to add password protection 
 * on a pdf file using iText jar.
 * @author codesjava
 */
public class PDFPasswordExample {
  public static void main(String args[]){
    try {
	String userPassword = "user123";
	String ownerPassword = "owner123";
 
	//Create Document instance.
	Document document = new Document();
 
	//Create OutputStream instance.
	OutputStream outputStream = 
	     new FileOutputStream(new File("D:\\TestPasswordFile.pdf"));
 
	//Create PDFWriter instance.
	PdfWriter pdfWriter = 
			PdfWriter.getInstance(document, outputStream);
 
        //Add password protection.
	pdfWriter.setEncryption(userPassword.getBytes(), 
		    ownerPassword.getBytes(),
                    PdfWriter.ALLOW_PRINTING, 
                    PdfWriter.ENCRYPTION_AES_256);
 
        //Open the document.
        document.open();
 
        //Add content to the document.
        document.add(new Paragraph("Hello world, this is a " +
            		"test pdf file with password protection."));
 
        //Close document and outputStream.
        document.close();
        outputStream.close();
 
        System.out.println("Pdf created successfully.");
    } catch (Exception e) {
	e.printStackTrace();
    }
  }
}

Output:

Pdf created successfully.

Download this example.
 
Previous Topic: How to merge two pdf files using itext in java?

 

Please follow and like us:
error








Copyright © 2019 CodesJava DMCA.com Protection Status