Secure PDF with Password Example
This program demonstrates securing a PDF file with a password.
Problem Statement
Write a Java program that encrypts a PDF file with a password using PDFBox.
Source Code
| 1 | import java.io.*; |
| 2 | import org.apache.pdfbox.pdmodel.*; |
| 3 | import org.apache.pdfbox.pdmodel.encryption.StandardProtectionPolicy; |
| 4 | public class SecurePDFExample { |
| 5 | public static void main(String[] args) { |
| 6 | System.out.println("Eduinq Secure PDF Example"); |
| 7 | try(PDDocument doc=new PDDocument()) { |
| 8 | doc.addPage(new PDPage()); |
| 9 | AccessPermission ap=new AccessPermission(); |
| 10 | StandardProtectionPolicy spp=new StandardProtectionPolicy("ownerpass","userpass",ap); |
| 11 | spp.setEncryptionKeyLength(128); |
| 12 | doc.protect(spp); |
| 13 | doc.save("secure.pdf"); |
| 14 | System.out.println("Eduinq PDF Secured Successfully"); |
| 15 | } catch(IOException e) { |
| 16 | System.out.println("Eduinq Exception: "+e.getMessage()); |
| 17 | } |
| 18 | } |
| 19 | } |
Program Output
Eduinq Secure PDF Example Eduinq PDF Secured Successfully
Explanation
PDFBox StandardProtectionPolicy applies password protection. - Owner and user passwords set with encryption length. - Exception handling ensures safe operations. - In enterprise systems, PDF security is used for confidential documents. Conclusion: Shows securing PDF files with passwords.