Encrypt & Decrypt PDFs - Java Sample Code

Sample code for using Apryse SDK to read encrypted (password protected) documents, secure a document with encryption, or remove encryption. Samples provided in Python, C++, C#, Java, Node.js (JavaScript), PHP, Ruby, Go and VB. Learn more about our Server SDK.

1//---------------------------------------------------------------------------------------
2// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
3// Consult legal.txt regarding legal and license information.
4//---------------------------------------------------------------------------------------
5
6import java.io.BufferedReader;
7import java.io.IOException;
8import java.io.InputStreamReader;
9
10import com.pdftron.common.PDFNetException;
11import com.pdftron.filters.FilterReader;
12import com.pdftron.filters.FlateEncode;
13import com.pdftron.filters.MappedFile;
14import com.pdftron.pdf.*;
15import com.pdftron.sdf.*;
16
17
18//---------------------------------------------------------------------------------------
19// This sample shows encryption support in PDFNet. The sample reads an encrypted document and
20// sets a new SecurityHandler. The sample also illustrates how password protection can
21// be removed from an existing PDF document.
22//---------------------------------------------------------------------------------------
23public class EncTest {
24 public static void main(String[] args) {
25 PDFNet.initialize(PDFTronLicense.Key());
26
27 // Relative path to the folder containing test files.
28 String input_path = "../../TestFiles/";
29 String output_path = "../../TestFiles/Output/";
30
31 // Example 1:
32 // secure a document with password protection and
33 // adjust permissions
34
35 // Open the test file
36 System.out.println("Securing an existing document ...");
37 try (PDFDoc doc = new PDFDoc((input_path + "fish.pdf"))) {
38 doc.initSecurityHandler();
39
40 // Perform some operation on the document. In this case we use low level SDF API
41 // to replace the content stream of the first page with contents of file 'my_stream.txt'
42 if (true) // Optional
43 {
44 System.out.println("Replacing the content stream, use flate compression...");
45
46 // Get the page dictionary using the following path: trailer/Root/Pages/Kids/0
47 Obj page_dict = doc.getTrailer().get("Root").value()
48 .get("Pages").value()
49 .get("Kids").value()
50 .getAt(0);
51
52 // Embed a custom stream (file mystream.txt) using Flate compression.
53 MappedFile embed_file = new MappedFile((input_path + "my_stream.txt"));
54 FilterReader mystm = new FilterReader(embed_file);
55 page_dict.put("Contents",
56 doc.createIndirectStream(mystm,
57 new FlateEncode(null)));
58 }
59
60 //encrypt the document
61
62 // Apply a new security handler with given security settings.
63 // In order to open saved PDF you will need a user password 'test'.
64 SecurityHandler new_handler = new SecurityHandler();
65
66 // Set a new password required to open a document
67 String user_password = "test";
68 new_handler.changeUserPassword(user_password);
69
70 // Set Permissions
71 new_handler.setPermission(SecurityHandler.e_print, true);
72 new_handler.setPermission(SecurityHandler.e_extract_content, false);
73
74 // Note: document takes the ownership of new_handler.
75 doc.setSecurityHandler(new_handler);
76
77 // Save the changes.
78 System.out.println("Saving modified file...");
79 doc.save((output_path + "secured.pdf"), SDFDoc.SaveMode.NO_FLAGS, null);
80 } catch (PDFNetException e) {
81 e.printStackTrace();
82 }
83
84 // Example 2:
85 // Opens the encrypted document and removes all of
86 // its security.
87 try (PDFDoc doc = new PDFDoc((output_path + "secured.pdf"))) {
88 //If the document is encrypted prompt for the password
89 if (!doc.initSecurityHandler()) {
90 boolean success = false;
91 System.out.println("The password is: test");
92 for (int count = 0; count < 3; count++) {
93 BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
94 System.out.println("A password required to open the document.");
95 System.out.print("Please enter the password: ");
96 String password = r.readLine();
97 if (doc.initStdSecurityHandler(password)) {
98 success = true;
99 System.out.println("The password is correct.");
100 break;
101 } else if (count < 3) {
102 System.out.println("The password is incorrect, please try again");
103 }
104 }
105 if (!success) {
106 System.out.println("Document authentication error....");
107 PDFNet.terminate();
108 }
109 }
110
111 //remove all security on the document
112 doc.removeSecurity();
113 doc.save(output_path + "not_secured.pdf", SDFDoc.SaveMode.NO_FLAGS, null);
114 } catch (Exception e) {
115 e.printStackTrace();
116 }
117
118 // Example 3:
119 // Encrypt/Decrypt a PDF using PDFTron custom security handler
120 System.out.println("-------------------------------------------------");
121 System.out.println("Encrypt a document using PDFTron Custom Security handler with a custom id and password...");
122 try (PDFDoc doc = new PDFDoc(input_path + "BusinessCardTemplate.pdf"))
123 {
124 // Create PDFTron custom security handler with a custom id. Replace this with your own integer
125 int custom_id = 123456789;
126 PDFTronCustomSecurityHandler custom_handler = new PDFTronCustomSecurityHandler(custom_id);
127
128 // Add a password to the custom security handler
129 String pass = "test";
130 custom_handler.changeUserPassword(pass);
131
132 // Save the encrypted document
133 doc.setSecurityHandler(custom_handler);
134 doc.save(output_path + "BusinessCardTemplate_enc.pdf", SDFDoc.SaveMode.NO_FLAGS, null);
135
136 System.out.println("Decrypt the PDFTron custom security encrypted document above...");
137 // Register the PDFTron Custom Security handler with the same custom id used in encryption
138 PDFNet.addPDFTronCustomHandler(custom_id);
139
140 PDFDoc doc_enc = new PDFDoc(output_path + "BusinessCardTemplate_enc.pdf");
141 doc_enc.initStdSecurityHandler(pass);
142 doc_enc.removeSecurity();
143 // Save the decrypted document
144 doc_enc.save(output_path + "BusinessCardTemplate_enc_dec.pdf", SDFDoc.SaveMode.NO_FLAGS, null);
145 System.out.println("Done. Result saved in BusinessCardTemplate_enc_dec.pdf");
146 } catch (Exception e) {
147 e.printStackTrace();
148 }
149 System.out.println("-------------------------------------------------");
150 System.out.println("Tests completed.");
151 PDFNet.terminate();
152 }
153}

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales