Encrypt and Decrypt Files

Requirements
View Demo

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.

Implementation steps

Step 1: Follow get started in your preferred web stack for WebViewer
Step 2: Enable the full API 
Step 3: Add the sample code provided in this guide

This full sample is included in the manual download of WebViewer.

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

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales