Client-side

PROTECT PDF

Secure your PDF files by adding a password and customizing user permissions completely in your browser.

🔒
Drag & drop a PDF file here, or click to browse
Supports single .pdf file

About Protect PDF Tool

Add strong encryption and password protection to your PDF files. Prevent unauthorized users from viewing, copying, or printing your sensitive document content. The tool uses AES encryption standards to secure files instantly.

The encryption key is generated locally on your machine, and files are locked inside your browser. No passwords or documents are ever shared, ensuring the highest level of security.

Developer Reference

Core Algorithm & Standalone Script

Standalone, zero-dependency JavaScript implementation powering this tool. Free to inspect, copy, and build upon.

import { encryptPDF } from 'https://cdn.jsdelivr.net/npm/@pdfsmaller/pdf-encrypt@1.0.2/+esm';

    let currentPdfBytes = null;
    let totalPages = 0;
    let fileNameStr = '';

    const uploadZone = document.getElementById('uploadZone');
    const fileInput = document.getElementById('fileInput');
    const configPanel = document.getElementById('configPanel');
    const fileNameEl = document.getElementById('fileName');
    const pageCountEl = document.getElementById('pageCount');
    const userPasswordInput = document.getElementById('userPassword');
    const ownerPasswordInput = document.getElementById('ownerPassword');
    const allowPrintingCheckbox = document.getElementById('allowPrinting');
    const allowCopyingCheckbox = document.getElementById('allowCopying');
    const allowModifyingCheckbox = document.getElementById('allowModifying');
    const protectBtn = document.getElementById('protectBtn');
    const loadingContainer = document.getElementById('loadingContainer');
    const resultContainer = document.getElementById('resultContainer');
    const resultInfo = document.getElementById('resultInfo');
    const downloadBtn = document.getElementById('downloadBtn');

    // Drag and drop event listeners
    ['dragenter', 'dragover'].forEach(eventName => {
      uploadZone.addEventListener(eventName, e => {
        e.preventDefault();
        uploadZone.classList.add('dragover');
      }, false);
    });

    ['dragleave', 'drop'].forEach(eventName => {
      uploadZone.addEventListener(eventName, e => {
        e.preventDefault();
        uploadZone.classList.remove('dragover');
      }, false);
    });

    uploadZone.addEventListener('drop', e => {
      const dt = e.dataTransfer;
      const files = dt.files;
      if (files.length > 0) handleFile(files[0]);
    });

    fileInput.addEventListener('change', e => {
      if (e.target.files.length > 0) handleFile(e.target.files[0]);
    });

    async function handleFile(file) {
      if (file.type !== 'application/pdf') return;
      fileNameStr = file.name;

      try {
        currentPdfBytes = await file.arrayBuffer();
        const { PDFDocument } = PDFLib;
        const pdf = await PDFDocument.load(currentPdfBytes);
        totalPages = pdf.getPageCount();

        fileNameEl.textContent = file.name;
        pageCountEl.textContent = `${totalPages} page${totalPages > 1 ? 's' : ''}`;
        
        configPanel.classList.remove('hidden');
        resultContainer.classList.add('hidden');
      } catch (err) {
        console.error(err);
        alert('Could not read PDF. Make sure it is not already password protected.');
      }
    }

    function formatBytes(bytes, decimals = 2) {
      if (bytes === 0) return '0 Bytes';
      const k = 1024;
      const dm = decimals < 0 ? 0 : decimals;
      const sizes = ['Bytes', 'KB', 'MB', 'GB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
    }

    protectBtn.addEventListener('click', async () => {
      if (!currentPdfBytes) return;

      const userPass = userPasswordInput.value;
      if (!userPass) {
        alert('User password is required to encrypt the PDF.');
        return;
      }

      configPanel.classList.add('hidden');
      loadingContainer.classList.remove('hidden');
      resultContainer.classList.add('hidden');

      try {
        const options = {
          allowPrinting: allowPrintingCheckbox.checked,
          allowCopying: allowCopyingCheckbox.checked,
          allowModifying: allowModifyingCheckbox.checked,
          algorithm: 'AES-256'
        };

        const ownerPass = ownerPasswordInput.value;
        if (ownerPass) {
          options.ownerPassword = ownerPass;
        }

        // Encrypt the PDF bytes
        const encryptedBytes = await encryptPDF(new Uint8Array(currentPdfBytes), userPass, options);
        const blob = new Blob([encryptedBytes], { type: 'application/pdf' });
        const blobUrl = URL.createObjectURL(blob);

        downloadBtn.href = blobUrl;
        const nameWithoutExt = fileNameStr.replace(/\.[^/.]+$/, "");
        downloadBtn.download = `${nameWithoutExt}_protected.pdf`;
        resultInfo.textContent = `PDF secured with AES-256 encryption. File size: ${formatBytes(blob.size)}.`;

        loadingContainer.classList.add('hidden');
        resultContainer.classList.remove('hidden');
      } catch (err) {
        console.error(err);
        alert('An error occurred while protecting the PDF: ' + err.message);
        loadingContainer.classList.add('hidden');
        configPanel.classList.remove('hidden');
      }
    });