By using iText library you can set the passwords to the PDF document by using the setEncryption method of PdfWriter class. The general form of the setEncryption method is shown below:
setEncryption(byte[] userPassword, byte[] ownerPassword, int permissions, int encryptionType)
- userPassword--an array of bytes that is the user password.
- ownerPassword--an array of bytes that is the owner password.
- permissions--permissions or restrictions that will be applied to the PDF document. These permissions can be AllowPrinting, AllowCopy, AllowScreenReaders, AllowFillIn, AllowAssembly, or AllowDegradedPrinting.
- encryptionType--the type of encryption. The encryption type can be one of the following STANDARD_ENCRYPTION_40, STANDARD_ENCRYPTION_128 or ENCRYPTION_AES128.
Example:
import java.awt.Desktop;
import java.io.File;
import java.io.FileOutputStream;
import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
public class PdfItext {
public static void main(String[] args){
setPasswords();
}
static void setPasswords(){
try{
//create a document object
Document doc = new Document();
//FileOutputStream object to write the pdf file
String path="d:/pdfdocprotected.pdf";
FileOutputStream fos=new FileOutputStream(path);
//get PdfWriter object
PdfWriter writer =PdfWriter.getInstance(doc,fos);
//convert strings of passwords to arrays of bytes
byte[] USER="Hello".getBytes();
byte[] OWNER="world".getBytes();
//spcify encryption of the document
writer.setEncryption(USER, OWNER, PdfWriter.ALLOW_PRINTING,
PdfWriter.ENCRYPTION_AES_256);
writer.createXmpMetadata();
//open the document for writing
doc.open();
//write a paragraph to the document
doc.add(new Paragraph("This PDF document is protected."));
//close the document
doc.close();
//view the result pdf file
Desktop dt=Desktop.getDesktop();
if(Desktop.isDesktopSupported()){
dt.open(new File(path));
}
}catch(Exception e){e.printStackTrace();}
}
}
When you run the example code above, you might get the dependency error as shown below. To fix the error, you will download the extra jar files from http://sourceforge.net/projects/itext/files/extrajars/. Then extract the zip file and add the bcprov-jdk15on-1.48.jar file to the project. After that, run the program again.