> For the complete documentation index, see [llms.txt](https://docs.apryse.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.apryse.com/web/get-started/samples/showcase-demo-password-protect.md).

# Password Protection Showcase Demo Code Sample

Open encrypted, password-protected PDFs using the correct password, and create new ones with built-in support for 128-bit or 256-bit AES encryption.

{% hint style="info" %}
**Requirements**

*These packages are required to use these features in production. Trial keys have unlimited access to all features*

<a href="/web/get-started/readme.md" class="button primary">Web SDK</a><a href="https://apryse.com/capabilities#Security" class="button primary">Package: Security</a><a href="https://showcase.apryse.com/password-protect" class="button primary">Live demo</a>
{% endhint %}

Open encrypted, password-protected PDFs using the correct password, and create new ones with built-in support for 128-bit or 256-bit AES encryption. Easily integrate custom security algorithms to further strengthen PDF protection.

This demo allows you to:

* Password-Protect PDFs with your own password
* Download encrypted password-protected PDF
* Support 128-bit or 256-bit AES encryption
* Customize encryption

**Implementation steps** To add Password Protection capability with WebViewer:

Step 1: Choose your [preferred web stack](/web/get-started/readme.md) Step 2: Add the ES6 JavaScript sample code provided in this guide

Once you generate your license key, it will automatically be included in your sample code below.

{% @apryse-license-key/apryse-license-key platform="WEB\_VIEWER" variant="compact" %}

<pre class="language-js" data-line-numbers><code class="lang-js">
// ES6 Compliant Syntax
// GitHub Copilot (VS Code Extension) - September 29, 2025
// File: password-protect/index.js

import WebViewer from '@pdftron/webviewer';

const licenseKey = '<code class="expression">visitor.claims.wvKey || "YOUR_WEBVIEWER_LICENSE_KEY"</code>';

const element = document.getElementById('viewer');

let theInstance = null;
let reloading = false;

const onLoad = async (instance) => {
  theInstance = instance;
  theInstance.Core.documentViewer.addEventListener('documentLoaded', () => {
    if (reloading) {
      reloading = false;
      return;
    }
    buttonDownload.disabled = true;
    buttonReload.disabled = true;
    buttonSetPass.disabled = false;
  });
};

WebViewer(
  {
    path: '/lib',
    licenseKey: licenseKey,
    initialDoc: 'https://pdftron.s3.amazonaws.com/downloads/pl/arrest-warrant-signed.pdf',
    enableFilePicker: true,
    fullAPI: true, //Required to use the PDFNet API
  },
  element
).then((instance) => {
  onLoad(instance);
});

const protectDocument = async (password) => {
    if (!password) {
      alert('Please enter a valid password');
      return;
    }
    const { PDFNet, documentViewer } = theInstance.Core;
    const doc = documentViewer.getDocument();
    if(doc.type !== 'pdf') {
      alert('Loaded document is not a PDF\nAborting ...');
      return;
    }
    
    await PDFNet.initialize();
    const PDFNetFile = await doc.getPDFDoc();
    const newHandler = await PDFNet.SecurityHandler.createDefault();

    // Set a new password required to open a document
    newHandler.changeUserPasswordUString(password);

    newHandler.setPermission(PDFNet.SecurityHandler.Permission.e_print, false);
    newHandler.setPermission(PDFNet.SecurityHandler.Permission.e_extract_content, true);

    PDFNetFile.setSecurityHandler(newHandler);
    buttonSetPass.disabled = true;
    buttonDownload.disabled = false;
    buttonReload.disabled = false;
  };

const reloadProtectedDoc = async () => {
    reloading = true;
    const doc = theInstance.Core.documentViewer.getDocument();
    const xfdfString = await theInstance.Core.annotationManager.exportAnnotations();
    const data = await doc.getFileData({
      xfdfString,
    });
    const arr = new Uint8Array(data);
    const blob = new Blob([arr], { type: 'application/pdf' });

    theInstance.UI.loadDocument(blob, { filename: doc.getFilename() });
};

// UI section
//

const labelMsg1 = document.createElement('label');
labelMsg1.textContent = 'Open encrypted password-protected documents, and encrypt PDFs with a password protection as well.';
labelMsg1.textContent += 'Apryse can support 128-bit or 256-bit AES encryption out of the box, or a custom security algorithm can be applied to the PDF.';
labelMsg1.className = 'formats-label';

const labelMsg2 = document.createElement('label');
labelMsg2.textContent = 'Use the Open File command in the WebViewer UI menu to upload a document without a password to try protecting';
labelMsg2.className = 'formats-label-bold';

const labelMsg3 = document.createElement('label');
labelMsg3.textContent = 'Set a password to protect the document';
labelMsg3.className = 'formats-label-bold';

const usernameInput = document.createElement('input');
usernameInput.type = 'text';
usernameInput.name = 'username';
usernameInput.autocomplete = 'username';
usernameInput.value = 'document-protection';
usernameInput.style.display = 'none'; // Hidden for accessibility
usernameInput.setAttribute('aria-hidden', 'true');

const passwordInput = document.createElement('input');
passwordInput.type = 'password';
passwordInput.name = 'password';
passwordInput.placeholder = 'Enter password';
passwordInput.autocomplete = 'Enter new password';

const passwordForm = document.createElement('form');
passwordForm.onsubmit = async (e) => {
  e.preventDefault();
  const password = passwordInput.value;
  await protectDocument(password);
};

const buttonSetPass = document.createElement('button');
buttonSetPass.type = 'submit';
buttonSetPass.textContent = 'Set Password';
buttonSetPass.className = 'btn-style';

passwordForm.appendChild(usernameInput);
passwordForm.appendChild(passwordInput);
passwordForm.appendChild(buttonSetPass);

// Create a button to download the protected PDF
const buttonDownload = document.createElement('button');
buttonDownload.className = 'btn-style';
buttonDownload.textContent = 'Download Protected Document';
buttonDownload.disabled = true;
buttonDownload.onclick = async () => {
  theInstance.UI.downloadPdf();
};

const buttonReload = document.createElement('button');
buttonReload.textContent = 'Reload Protected Document';
buttonReload.className = 'btn-style';
buttonReload.disabled = true;
buttonReload.onclick = async () => {
  reloadProtectedDoc();
};

// Create a container for all controls (labels, buttons, etc.)
const controlsContainer = document.createElement('div');
controlsContainer.className = 'container-style';

controlsContainer.appendChild(labelMsg1);
controlsContainer.appendChild(document.createElement('br'));
controlsContainer.appendChild(labelMsg2);
controlsContainer.appendChild(document.createElement('br'));
controlsContainer.appendChild(labelMsg3);
controlsContainer.appendChild(passwordForm);
controlsContainer.appendChild(document.createElement('br'));
controlsContainer.appendChild(buttonDownload);
controlsContainer.appendChild(buttonReload);
element.insertBefore(controlsContainer, element.firstChild);

</code></pre>

[View the full sample on GitHub](https://github.com/ApryseSDK/webviewer-samples/tree/main/showcase-demos-playground)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.apryse.com/web/get-started/samples/showcase-demo-password-protect.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
