Sample JavaScript code for using Apryse SDK to read encrypted (password protected) documents, secure a document with encryption, or remove encryption. Learn more about our Web SDK.
1//---------------------------------------------------------------------------------------
2// Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
3// Consult legal.txt regarding legal and license information.
4//---------------------------------------------------------------------------------------
5(exports => {
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29 exports.runEncTest = () => {
30 const PDFNet = exports.Core.PDFNet;
31
32 const main = async () => {
33 console.log('Beginning Test');
34 let ret = 0;
35 // Relative path to the folder containing test files.
36 const inputUrl = '../TestFiles/';
37 let doc = null;
38 // Example 1:
39 // secure a PDF document with password protection and adjust permissions
40 try {
41 console.log('Running Sample 1');
42 doc = await PDFNet.PDFDoc.createFromURL(inputUrl + 'fish.pdf');
43 doc.initSecurityHandler();
44 doc.lock();
45 console.log('PDFNet and PDF document initialized and locked');
46
47 const performOperation = true; // optional parameter
48
49 // Perform some operation on the document. In this case we use low level SDF API
50 // to replace the content stream of the first page with contents of file 'my_stream.txt'
51 // Results in fish.pdf becoming a pair of feathers.
52 if (performOperation) {
53 console.log('Replacing the content stream, use Flate compression...');
54 // Get the page dictionary using the following path: trailer/Root/Pages/Kids/0
55 const pageTrailer = await doc.getTrailer();
56 const pageRoot = await pageTrailer.get('Root');
57 const pageRootValue = await pageRoot.value();
58 const pages = await pageRootValue.get('Pages');
59 const pagesVal = await pages.value();
60 const kids = await pagesVal.get('Kids');
61 const kidsVal = await kids.value();
62 const pageDict = await kidsVal.getAt(0);
63
64 const embedFile = await PDFNet.Filter.createURLFilter(inputUrl + 'my_stream.txt');
65 const mystm = await PDFNet.FilterReader.create(embedFile);
66
67 const emptyFilter = new PDFNet.Filter('0');
68 const flateEncode = await PDFNet.Filter.createFlateEncode(emptyFilter);
69
70 const indStream = await doc.createIndirectStreamFromFilter(mystm, flateEncode);
71 await pageDict.put('Contents', indStream);
72 }
73
74 // Encrypt the document
75 // Apply a new security handler with given security settings.
76 // In order to open saved PDF you will need a user password 'test'.
77 const newHandler = await PDFNet.SecurityHandler.createDefault();
78
79 // Set a new password required to open a document
80 newHandler.changeUserPasswordUString('test');
81 console.log("Setting password to 'test'");
82
83 // Set Permissions
84 newHandler.setPermission(PDFNet.SecurityHandler.Permission.e_print, false);
85 newHandler.setPermission(PDFNet.SecurityHandler.Permission.e_extract_content, true);
86
87 // Note: document takes the ownership of newHandler.
88 doc.setSecurityHandler(newHandler);
89
90 // Save the changes
91 console.log('Saving modified file...');
92
93 const docbuf = await doc.saveMemoryBuffer(PDFNet.SDFDoc.SaveOptions.e_linearized);
94 saveBufferAsPDFDoc(docbuf, 'secured.pdf');
95 } catch (err) {
96 console.log(err);
97 console.log(err.stack);
98 ret = 1;
99 }
100
101 // Example 2:
102 // Opens an encrypted PDF document and removes its security.
103 try {
104 console.log('Running Sample 2');
105 const securedDoc = doc;
106
107 if (!(await securedDoc.initSecurityHandler())) {
108 let success = false;
109 console.log("The password has been set to : 'test'");
110 const passwordsToTry = ['password', 'testy', 'test'];
111
112 for (let count = 0; count < passwordsToTry.length; count++) {
113 const candidate = passwordsToTry[count];
114 console.log("Trying password candidate: '" + candidate + "'");
115 if (await securedDoc.initStdSecurityHandlerUString(candidate)) {
116 success = true;
117 console.log('The password is correct');
118 break;
119 } else {
120 console.log('The password is incorrect.');
121 }
122 }
123 if (!success) {
124 console.log('Document authentication error...');
125 ret = 1;
126 return ret;
127 }
128 }
129 securedDoc.lock();
130
131 console.log('PDF document initialized and locked');
132 const hdlr = await securedDoc.getSecurityHandler();
133
134 console.log('Document Open Password: ' + (await hdlr.isUserPasswordRequired()));
135 console.log('Permissions Password: ' + (await hdlr.isMasterPasswordRequired()));
136 console.log('Permissions: ');
137 console.log("\tHas 'owner' permissions: " + (await hdlr.getPermission(PDFNet.SecurityHandler.Permission.e_owner)));
138
139 console.log('\tOpen and decrypt the document: ' + (await hdlr.getPermission(PDFNet.SecurityHandler.Permission.e_doc_open)));
140 console.log('\tAllow content extraction: ' + (await hdlr.getPermission(PDFNet.SecurityHandler.Permission.e_extract_content)));
141 console.log('\tAllow full document editing: ' + (await hdlr.getPermission(PDFNet.SecurityHandler.Permission.e_doc_modify)));
142 console.log('\tAllow printing: ' + (await hdlr.getPermission(PDFNet.SecurityHandler.Permission.e_print)));
143 console.log('\tAllow high resolution printing: ' + (await hdlr.getPermission(PDFNet.SecurityHandler.Permission.e_print_high)));
144 console.log('\tAllow annotation editing: ' + (await hdlr.getPermission(PDFNet.SecurityHandler.Permission.e_mod_annot)));
145 console.log('\tAllow form fill: ' + (await hdlr.getPermission(PDFNet.SecurityHandler.Permission.e_fill_forms)));
146 console.log('\tAllow content extraction for accessibility: ' + (await hdlr.getPermission(PDFNet.SecurityHandler.Permission.e_access_support)));
147 console.log('\tAllow document assembly: ' + (await hdlr.getPermission(PDFNet.SecurityHandler.Permission.e_assemble_doc)));
148
149 // remove all security on the document
150 securedDoc.removeSecurity();
151
152 const docbuf = await securedDoc.saveMemoryBuffer(PDFNet.SDFDoc.SaveOptions.e_linearized);
153 saveBufferAsPDFDoc(docbuf, 'not_secured.pdf');
154 console.log('done');
155 } catch (err) {
156 console.log(err.stack);
157 ret = 1;
158 }
159 return ret;
160 };
161
162 // add your own license key as the second parameter, e.g. PDFNet.runWithCleanup(main, 'YOUR_LICENSE_KEY')
163 PDFNet.runWithCleanup(main);
164 };
165})(window);
166// eslint-disable-next-line spaced-comment
167//# sourceURL=EncTest.js
Did you find this helpful?
Trial setup questions?
Ask experts on DiscordNeed other help?
Contact SupportPricing or product questions?
Contact Sales