We can Decrypt any PDF using Java by using the external library PDFBox. We can Decrypt and remove the Access Permission from any PDF using JAVA, but we must remember the Owner Password of the PDF to Decrypt it, otherwise, we can not decrypt it.
In this program, you will see how you can take an encrypted PDF file as input and how you can decrypt it to access or to read the PDF file. You will see the PDFBox library used for the following procedure.
Input : Encrypted PDF file Output : Decrypted PDF file
Maven Dependency for PDFBox :
<dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> <version>2.0.21</version> </dependency>
Steps to Decrypt a PDF
1. Load the PDF Document
Load the PDF file using load() static method (we can access it by using the class name) of class PDDocument. The load() method will accept the PDF file as a parameter. Here Owner Password is compulsory otherwise we can not Decrypt it.
File f = new File("path_of_PDFfile"); PDDocument pdd = PDDocument.load("object_of_file","Owner_password");
2. Call “setAllSecurityToBeRemoved(bool)” method
After loading PDF file call setAllSecurityToBeRemoved(bool) method using object of PDDocument class. It will remove the Access Permission from PDF and allow all users to access it. In setAllSecurityToBeRemoved(bool) pass boolean(True/False) as a parameter. Pass true if we want to perform Decryption operation otherwise false.
3. Save and Close File
After Decrypting the PDF save and close the file to make a change in it.
Executable Code to Decrypt PDF:
Let’s have a look at the given below screenshots for a better understanding and you will see how you can decrypt the given PDF file and access to read it. In this screenshot, you will see a PDF encrypted file that is password protected which means you simply need permission or password to grant access to the PDF file.
Once you entered the correct password then you will be able to access and read the PDF file. Now, If you want to decrypt it by using Java code then you need to write code as shown and need to execute the following program as shown in the screenshot given below.
Now, After the successful execution of the above program then you don’t need any password to access the PDF file which means your PDF file is decrypted now and you can directly access and read it.
Here is the video where you will see the decryption procedure and you will see exactly how it will work. So, in this way you can change access permission of any PDF which will allow all users to access it easily.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.