Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

Use PDFKit’s userPassword option when you create the document. Add an ownerPassword and permissions if you need separate control over opening, printing, copying, or editing. Select pdfVersion: '1.7ext3' for PDFKit’s documented AES-256 mode when your target viewers support it. If another library already creates the PDF, encrypt the finished file with qpdf instead. Do not use pdf-lib alone for this step: its package documentation says encrypted documents are not currently supported.

Encrypt a PDF while PDFKit creates it

PDFKit encrypts a document when a user password is supplied in the PDFDocument constructor. The password is not added after the file is written; it is part of the PDF’s security dictionary as PDFKit generates the file.

Complete Node.js example

const PDFDocument = require('pdfkit');
const fs = require('node:fs');

const userPassword = process.env.PDF_USER_PASSWORD;
const ownerPassword = process.env.PDF_OWNER_PASSWORD;

if (!userPassword || !ownerPassword) {
  throw new Error('Set PDF_USER_PASSWORD and PDF_OWNER_PASSWORD first');
}

const doc = new PDFDocument({
  userPassword,
  ownerPassword,
  pdfVersion: '1.7ext3',
  permissions: {
    printing: 'highResolution',
    modifying: false,
    copying: false
  }
});

doc.pipe(fs.createWriteStream('protected.pdf'));
doc.fontSize(18).text('Confidential report');
doc.moveDown().fontSize(11).text('This document requires a password to open.');
doc.end();

Run it with secrets supplied by the process environment rather than committed source:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
PDF_USER_PASSWORD='reader-secret' PDF_OWNER_PASSWORD='admin-secret' node generate-pdf.js

Opening protected.pdf in a conforming viewer should prompt for the user password. Keep the output stream open until the end event has completed if your application needs to report that the file is fully written.

#1 Best Overall
PDF Extra 2024| Complete PDF Reader and Editor | Create, Edit, Convert, Combine, Comment, Fill & Sign PDFs | Lifetime License | 1 Windows PC | 1 User [PC Online code]
  • EDIT text, images & designs in PDF documents. ORGANIZE PDFs. Convert PDFs to Word, Excel & ePub.
  • READ and Comment PDFs – Intuitive reading modes & document commenting and mark up.
  • CREATE, COMBINE, SCAN and COMPRESS PDFs
  • FILL forms & Digitally Sign PDFs. PROTECT and Encrypt PDFs
  • LIFETIME License for 1 Windows PC or Laptop. 5GB MobiDrive Cloud Storage Included.

User and owner passwords

  • User password: required to open the encrypted document. This is the password you normally give to a recipient.
  • Owner password: controls the permissions and administrative password in PDF’s standard security handler. It can be different from the user password.

Use long, randomly generated values and store them in a secret manager, environment injection system, or equivalent deployment facility. Never put production passwords in a repository, a Docker image layer, or a URL.

Choose the encryption strength with pdfVersion

PDFKit maps its documented PDF versions to encryption algorithms:

pdfVersion Documented algorithm Security implication
1.3 40-bit RC4 Weak; qpdf documentation describes 40-bit encryption as easily brute-forced.
1.4 or 1.5 128-bit RC4 Legacy and considered insecure by qpdf guidance.
1.6 or 1.7 128-bit AES Stronger than the RC4 choices, but still not the preferred maximum in this comparison.
1.7ext3 256-bit AES Preferred documented strength when all target viewers support the required PDF version.

Use 1.7ext3 for new systems after checking the PDF viewers used by your customers. If an older viewer cannot open that file, select a compatible version deliberately rather than silently falling back to a weak cipher.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Control printing, copying, and editing

PDFKit accepts a permissions object. The guide documents controls for printing, modifying, and copying; printing can be set to 'highResolution' where supported. For example:

const doc = new PDFDocument({
  userPassword: process.env.PDF_USER_PASSWORD,
  ownerPassword: process.env.PDF_OWNER_PASSWORD,
  pdfVersion: '1.7ext3',
  permissions: {
    printing: 'highResolution',
    modifying: false,
    copying: false
  }
});

These flags are restrictions requested by the encrypted PDF’s security handler, not an absolute data-loss-prevention system. PDFKit warns that applications decide whether to honor them. Once somebody can decrypt and read the content, software that ignores permission flags can copy or modify it. Treat permissions as viewer-level policy, not as a guarantee that content can never be extracted.

Password handling in a real Node.js service

Generate passwords outside application code

Use your deployment platform’s secret store or an equivalent mechanism. Fail fast when a required variable is absent, as the example does. Do not log the values, include them in error messages, or send them alongside the PDF in the same unprotected channel.

Rank #2
PDF Extra Ultimate | Complete PDF Reader and Editor | Create, Edit, Convert, Combine, Comment, Fill & Sign PDFs | Yearly License | 1 Windows PC & 2 Mobile Devices | 1 User
  • EDIT text, images & designs in PDF documents. ORGANIZE PDFs. Convert PDFs to Word, Excel & ePub.
  • READ and Comment PDFs – Intuitive reading modes & document commenting and mark up.
  • CREATE, COMBINE, SCAN and COMPRESS PDFs
  • FILL forms & Digitally Sign PDFs. PROTECT and Encrypt PDFs
  • 1 Year License for 1 Windows & 2 Mobile (Android and/or iOS) devices.

Deliver the password separately

Send the encrypted file and its opening password through separate channels. For a batch job, record only a secret identifier or a hash used for verification, not the plaintext password. Rotate secrets according to your organization’s policy; changing a password requires producing a newly encrypted PDF.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use streams for large documents

PDFKit writes to a stream, so it can avoid holding the entire output in memory. Handle error events on both the document and destination stream, and wait for the destination’s finish event before marking a job successful.

const output = fs.createWriteStream('protected.pdf');
const doc = new PDFDocument({
  userPassword: process.env.PDF_USER_PASSWORD,
  ownerPassword: process.env.PDF_OWNER_PASSWORD,
  pdfVersion: '1.7ext3'
});

doc.on('error', (err) => console.error('PDF generation failed', err));
output.on('error', (err) => console.error('PDF write failed', err));
output.on('finish', () => console.log('protected.pdf is complete'));

doc.pipe(output);
doc.text('Confidential report');
doc.end();

When another Node.js library generated the PDF

Separate layout from encryption. Use the renderer that produces the required fonts, pagination, charts, or forms, then run qpdf’s standard security handler over the completed file. qpdf documents distinct user and owner passwords, encryption dictionaries, and AES-256 as its secure standard-handler choice.

Typical qpdf post-processing command

qpdf --encrypt 
  "$PDF_USER_PASSWORD" 
  "$PDF_OWNER_PASSWORD" 
  256 
  --print=full 
  --modify=none 
  --extract=n 
  -- input.pdf protected.pdf

Exact qpdf option syntax can vary by installed release, so consult the qpdf PDF encryption documentation for the version deployed in production. The important model is unchanged: the first password is for opening, the second is the owner password, and the encryption key length is selected explicitly. Run qpdf in a controlled worker, restrict temporary-file permissions, and delete unencrypted intermediates after successful encryption.

Verify the result

  1. Open the output in every viewer you officially support and confirm that a password is requested.
  2. Test the intended owner and user passwords separately.
  3. Check printing, copying, and modification behavior where those permissions matter.
  4. Inspect job logs for failures without logging either password.

Compatibility is a product decision: a stronger PDF version may be unacceptable if your recipients use old readers. Conversely, choosing an old RC4 mode solely for compatibility leaves a known weakness.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Why pdf-lib is not the encryption step

pdf-lib is suitable for creating and modifying many PDFs, but its package documentation explicitly states: “pdf-lib does not currently support encrypted documents.” You can use it to prepare content, then pass the resulting file to a tool that supports encryption, such as qpdf. Do not describe a pdf-lib-only pipeline as password protection.

Rank #3
MobiPDF Lifetime - Professional PDF Editor for Windows | Edit, Sign & Convert PDFs | Best Adobe Acrobat Pro Alternative | Lifetime License
  • Edit PDFs with Ease. Modify text, images, and layouts directly within your PDF documents.
  • Convert & Organize. Export PDFs to Word, Excel, or ePub, and organize files with ease.
  • Read & Annotate. Enjoy intuitive reading modes and powerful tools to comment, highlight, and mark up PDFs.
  • Create & Manage PDFs. Create new PDFs, combine multiple files, scan documents, and compress for easy sharing.
  • Fill & Sign Forms. Complete forms and digitally sign documents with secure e-signature tools.

Common failures and fixes

The viewer opens the file without asking for a password

Confirm that userPassword was defined and non-empty in the constructor that created this particular file. Make sure you are opening the newly written output, not a cached or previous unencrypted copy, and wait for the output stream to finish.

The password is always rejected

Check for shell quoting, trailing whitespace, newline characters, and differences between the secret used for generation and the one sent to the recipient. Environment variables containing special characters must be passed without accidental interpolation.

Printing or copying is still possible

Permission flags are advisory. The viewer may not enforce them, or the file may have been opened with an owner password that permits the operation. Test with the exact applications your recipients use; do not promise that permissions prevent extraction by hostile software.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

An older reader reports an unsupported encryption revision

The selected PDF version or AES-256 mode may be too new. Test a compatible PDFKit version such as 1.6 or 1.7, understanding that PDFKit documents those as 128-bit AES rather than AES-256. Do not use 40-bit or 128-bit RC4 for sensitive new documents merely to satisfy an unmaintained reader without assessing the risk.

qpdf cannot read the input

Ensure the renderer closed the file before qpdf starts, and verify that the input is a complete PDF rather than an HTML error page or a zero-byte file. Preserve the original until the encrypted output passes verification.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Performance, deployment, and cost considerations

In-process PDFKit encryption avoids a second process and an intermediate file, which is useful for API responses and serverless functions. qpdf adds process startup and temporary-I/O overhead but lets you keep a preferred renderer and apply one consistent encryption policy to PDFs produced by several libraries. Benchmark your own document sizes and concurrency; no universal speed figure applies to every Node.js runtime, font set, or deployment.

Rank #4
MixPad Free Multitrack Recording Studio and Music Mixing Software [Download]
  • Create a mix using audio, music and voice tracks and recordings.
  • Customize your tracks with amazing effects and helpful editing tools.
  • Use tools like the Beat Maker and Midi Creator.
  • Work efficiently by using Bookmarks and tools like Effect Chain, which allow you to apply multiple effects at a time
  • Use one of the many other NCH multimedia applications that are integrated with MixPad.

For either approach, limit concurrent jobs, stream output where possible, use restrictive file permissions, and monitor failed writes. Encryption does not fix an insecure transport: serve downloads over HTTPS and authenticate the endpoint that releases either the PDF or its password.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Or skip the browser setup

If your workflow also needs website screenshots for documentation or reports, ScreenshotNeo provides a single HTTP request that returns a PNG, JPEG, WebP, or PDF. It accepts cookie and consent banners as a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each cleanup step can be disabled. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the page verdict and billing status in headers. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

See the ScreenshotNeo API documentation for output and option details. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

Frequently Asked Questions

Can I add a password to a PDF after PDFKit has written it?

Yes. Encrypt the completed file with qpdf, or regenerate it with PDFKit and a user password. The post-processing route is useful when a different renderer produced the original.

Is an owner password required?

No. PDFKit documents it as optional. It is useful when you want a separate administrative password and permission settings.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Are PDF permission flags legally or technically unbreakable?

No. They depend on conforming viewer applications honoring them and should not be treated as a guarantee against copying or modification.

What should I use if recipients have old PDF readers?

Test the readers first and choose the strongest PDFKit version they support. Older compatible modes may use weaker algorithms, so document the trade-off.

Quick Recap

Bestseller No. 1
PDF Extra 2024| Complete PDF Reader and Editor | Create, Edit, Convert, Combine, Comment, Fill & Sign PDFs | Lifetime License | 1 Windows PC | 1 User [PC Online code]
PDF Extra 2024| Complete PDF Reader and Editor | Create, Edit, Convert, Combine, Comment, Fill & Sign PDFs | Lifetime License | 1 Windows PC | 1 User [PC Online code]
READ and Comment PDFs – Intuitive reading modes & document commenting and mark up.; CREATE, COMBINE, SCAN and COMPRESS PDFs
$99.99
Bestseller No. 2
PDF Extra Ultimate | Complete PDF Reader and Editor | Create, Edit, Convert, Combine, Comment, Fill & Sign PDFs | Yearly License | 1 Windows PC & 2 Mobile Devices | 1 User
PDF Extra Ultimate | Complete PDF Reader and Editor | Create, Edit, Convert, Combine, Comment, Fill & Sign PDFs | Yearly License | 1 Windows PC & 2 Mobile Devices | 1 User
READ and Comment PDFs – Intuitive reading modes & document commenting and mark up.; CREATE, COMBINE, SCAN and COMPRESS PDFs
$83.88
Bestseller No. 3
MobiPDF Lifetime - Professional PDF Editor for Windows | Edit, Sign & Convert PDFs | Best Adobe Acrobat Pro Alternative | Lifetime License
MobiPDF Lifetime - Professional PDF Editor for Windows | Edit, Sign & Convert PDFs | Best Adobe Acrobat Pro Alternative | Lifetime License
Edit PDFs with Ease. Modify text, images, and layouts directly within your PDF documents.; Convert & Organize. Export PDFs to Word, Excel, or ePub, and organize files with ease.
$99.99
Bestseller No. 4
MixPad Free Multitrack Recording Studio and Music Mixing Software [Download]
MixPad Free Multitrack Recording Studio and Music Mixing Software [Download]
Create a mix using audio, music and voice tracks and recordings.; Customize your tracks with amazing effects and helpful editing tools.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.