Password protect a PDF in C#
Encrypt a PDF so it needs a password to open, and limit what readers may do with it.
Short answer
Section titled “Short answer”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.
#:package PdfNetStack@1.2.0using 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 defaultdoc.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}");dotnet add package PdfNetStackPermissions 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.
Related
Section titled “Related”- Encryption
- Remove a password from a PDF
- Command line:
pdfnetstack encrypt in.pdf out.pdf --user-password u --owner-password o --allow print,copy - API: PdfSecurity, PdfPermissions