Skip to content

Password protect a PDF in C#

Since 1.0View as Markdown

Encrypt a PDF so it needs a password to open, and limit what readers may do with it.

Call doc.Security.Encrypt with a user password, an owner password and the permissions to grant, then save. The user password opens the file with those permissions; the owner password gives full access. New protection is AES-256 unless you pass PdfEncryption.Aes128.

recipe-password-protect-pdf.cs
#:package PdfNetStack@1.2.0
using PdfNetStack;
PdfDocument doc = PdfDocument.Open("report.pdf");
doc.Security.Encrypt(
userPassword: "open-me", // needed to open the file
ownerPassword: "owner-secret", // needed to change it
permissions: PdfPermissions.Print | PdfPermissions.CopyContent); // AES-256 by default
doc.Save("report-protected.pdf");
PdfDocument check = PdfDocument.Open("report-protected.pdf", password: "open-me");
Console.WriteLine($"Opened with the user password: {check.Pages.Count} pages, {check.Security.Permissions}");
Terminal window
dotnet add package PdfNetStack

Permissions are Print, PrintHighQuality, Modify, CopyContent, Annotate, FillForms, ExtractForAccessibility and Assemble, combined with |. A document opened with only the user password can be read but not saved. One opened with the owner password keeps its passwords and permissions when saved.