We can encrypt PDF files to protect their content. In this case, you need to enter a password to view or edit the content.Dynamsoft Document ViewerIt is a JavaScript SDK for document scanning and viewing, which can encrypt and decrypt PDF files on the front end. In this article, we will explore how to use it.
Open a PDF file using Dynamsoft Document Viewer
1. Create a new HTML file containing the following templates.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"> <title>Browse Viewer</title> <style> </style> </head> <body> </body> <script> </script> </html>
2. Include the file of the Dynamsoft Document Viewer in the page.
<script src="/npm/[email protected]/dist/"></script> <link rel="stylesheet" href="/npm/[email protected]/dist/">
3. Initialize the Dynamsoft Document Viewer with the license. Can behereApply for a certificate.
= "DLS2eyJoYW5kc2hha2VDb2RlIjoiMjAwMDAxLTE2NDk4Mjk3OTI2MzUiLCJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSIsInNlc3Npb25QYXNzd29yZCI6IndTcGR6Vm05WDJrcEQ5YUoifQ=="; //one-day trial = "/npm/[email protected]/dist/engine";// Lead to a folder containing the distributed WASM files await ();
4. Create a new document instance.
const docManager = ; const doc = ();
5. Create a Browse Viewer instance, bind it to a container, and use it to view the document we just created.
HTML:
<div ></div>
JavaScript:
const browseViewer = new ({ container: ("viewer"), }); ();
CSS:
#viewer { width: 320px; height: 480px; }
6. Useinput
Select a PDF file and load it into the document instance, which can then be viewed with Browse Viewer.
HTML:
<label> Select a PDF file to load: <br/> <input type="file" name="files" accept=".pdf" onchange="filesSelected()"/> </label>
JavaScript:
async function filesSelected(){ let filesInput = ("files"); let files = ; if (>0) { const file = files[0]; const blob = await readFileAsBlob(file); await (blob); // load the PDF file } } function readFileAsBlob(file){ return new Promise((resolve, reject) => { const fileReader = new FileReader(); = async function(e){ const response = await fetch(); const blob = await (); resolve(blob); }; = function () { reject('oops, something went wrong.'); }; (file); }) }
Open a password-protected PDF file
If the PDF is password protected, an error will be thrown when opening using the default configuration, prompting us that we need to enter a password to open it.
Error: Failed to read the PDF file because it's encrypted and the correct password is not provided.
We can catch this error and ask the user to enter a password.
HTML:
<div class="modal input-modal"> <div> <label> Please input the password: </label> <br/> <input type="password" /> <br/> <button >Okay</button> </div> </div>
CSS:
.modal { display: flex; align-items: flex-start; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); min-width: 250px; border: 1px solid gray; border-radius: 5px; background: white; z-index: 9999; padding: 10px; visibility: hidden; } . { visibility: inherit; }
JavaScript:
function filesSelected(){ //... try { await (blob); } catch (error) { if ( === -80202) { askForPassword(); } } } function askForPassword(){ ("password").value = ""; //clear previous password ("input-modal")[0].("active"); } ("okayBtn").addEventListener("click",async function(){ ("input-modal")[0].("active"); try { await ({fileData:blob,password:("password").value}); } catch (error) { alert(error); } })
Password needs to be passed inloadSource
method:
await ({fileData:blob,password:("password").value});
Save as a password protected PDF file
Save the document as PDF without setting a password, and you can create a decrypted PDF file. If the password is set, an encrypted PDF file will be created.
<div> <label>Set a password: <input type="password" /> </label> </div> <script> let newPassword = ("newPassword").value; let blob; if (newPassword) { blob = await ({password:newPassword}); }else{ blob = await (); } </script>
This is the end of this article about the implementation of PDF encryption and decryption of JavaScript front-end. For more related JavaScript PDF encryption and decryption content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!