Apache PDFBox provides way to protect your pdf by adding a password protection. In this post we will see an example on encrypting pdf using apache pdfbox.
The important classes that are required for encrypting pdf using apache pdfbox are
1) org.apache.pdfbox.pdmodel.encryption.AccessPermission
This class is used to specify the permissions given on the pdf. Few of the permissions that can be specified are
a)
setCanPrint(boolean allowPrinting) print the document
b)
setCanModify(boolean allowModifications) modify the content of the document
c)
setCanExtractContent(boolean allowExtraction) copy or extract content of the document
d)
setCanModifyAnnotations(boolean allowAnnotationModification) add or modify annotations
e)
setCanFillInForm(boolean allowFillingInForm) fill in interactive form fields
f)
setCanExtractForAccessibility(boolean allowExtraction) extract text and graphics for accessibility to visually impaired people
g)
setCanAssembleDocument(boolean allowAssembly) assemble the document
h)
setCanPrintDegraded(boolean canPrintDegraded) print in degraded quality
2) org.apache.pdfbox.pdmodel.encryption.StandardProtectionPolicy
This class is used for the protection policy to add to a document for password-based protection. The constructor takes 3 parameters –
StandardProtectionPolicy(String ownerPassword, String userPassword, AccessPermission permissions)
ownerPassword – The owner’s password.
userPassword – The users’s password.
permissions – The access permissions given to the user.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
package com.kscodes.examples.pdfbox; import java.io.FileInputStream; import java.io.IOException; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.encryption.AccessPermission; import org.apache.pdfbox.pdmodel.encryption.StandardProtectionPolicy; public class PdfEncryptExample { public static void main(String args[]) { try { // load Document object with existing pdf. PDDocument pdDocument = PDDocument.load(new FileInputStream("K:\\Kscodes\\pdf\\pdf-sample.pdf")); // Define an encryption key length int encryptionKeyLength = 128; // Setup the Access permissions. AccessPermission accessPermission = new AccessPermission(); // StandardProtectionPolicy class takes owner password, user // password and the permissions StandardProtectionPolicy standardProtectionPolicy = new StandardProtectionPolicy("kscodes", "password", accessPermission); standardProtectionPolicy.setEncryptionKeyLength(encryptionKeyLength); // time to protect the pdf pdDocument.protect(standardProtectionPolicy); pdDocument.save("K:\\Kscodes\\pdf\\pdf-sample.pdf"); pdDocument.close(); System.out.println("PDF is now password protected!!!"); } catch (IOException ioe) { System.out.println("Error while reading pdf" + ioe.getMessage()); } } } |
Output