如何设置PDF的密码和权限
密码保护包括对文档进行加密,以限制未经授权的访问。 通常包括两种类型的密码:用户密码(或打开密码),用于打开文档,以及所有者密码(或权限密码),用于控制编辑、打印和其他操作的权限。
IronPDF支持您现有和新PDF文件所需的所有密码和权限功能。 可以应用细粒度的元数据和安全设置,包括限制 PDF 文档不可打印、只读和加密的功能; 支持 128 位加密、解密和密码保护。
开始使用IronPDF
立即在您的项目中开始使用IronPDF,并享受免费试用。
如何在 C# 中使用密码和权限保护 PDF

- 下载 C# 库以用密码保护 PDF
- 设置OwnerPassword属性以防止 PDF 文件被编辑
- 设置UserPassword属性以防止PDF文件被打开
- 使用 128 位加密技术加密 PDF 文件
- 为
FromFile
方法提供密码以打开PDF文档
为PDF设置密码
我们有一个示例PDF文件,我们想使用IronPDF进行保护。 让我们执行以下代码以为PDF添加密码。 在此示例中,我们将使用密码password123。
:path=/static-assets/pdf/content-code-examples/how-to/pdf-permissions-passwords-add-password.cs
using IronPdf;
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Secret Information:</h1> Hello World");
// Password to edit the pdf
pdf.SecuritySettings.OwnerPassword = "123password";
// Password to open the pdf
pdf.SecuritySettings.UserPassword = "password123";
pdf.SaveAs("protected.pdf");
结果是以下 PDF 文件,您可以通过输入密码 password123 查看。
打开一个有密码的PDF文件
本节介绍如何打开有密码的 PDF。 PdfDocument.FromFile
方法有一个第二个可选参数,该参数是密码。 请将正确的密码提供给此参数以打开PDF。
:path=/static-assets/pdf/content-code-examples/how-to/pdf-permissions-passwords-open-password.cs
using IronPdf;
var pdf = PdfDocument.FromFile("protected.pdf", "password123");
//... perform PDF-tasks
pdf.SaveAs("protected_2.pdf"); // Saved as another file
高级安全与权限设置
PdfDocument 对象还具有您可以设置的 MetaData 字段,例如 Author 和 ModifiedDate。 您还可以禁用用户注释、用户打印等功能,如下所示:
:path=/static-assets/pdf/content-code-examples/how-to/pdf-permissions-passwords-advanced.cs
using IronPdf;
// Open an Encrypted File, alternatively create a new PDF from HTML
var pdf = PdfDocument.FromFile("protected.pdf", "password123");
// Edit file security settings
// The following code makes a PDF read only and will disallow copy & paste and printing
pdf.SecuritySettings.RemovePasswordsAndEncryption();
pdf.SecuritySettings.MakePdfDocumentReadOnly("secret-key");
pdf.SecuritySettings.AllowUserAnnotations = false;
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
pdf.SecuritySettings.AllowUserFormData = false;
pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.FullPrintRights;
// Save the secure PDF
pdf.SaveAs("secured.pdf");
权限设置与文档密码相关,并按以下方式行为。 例如,将AllowUserCopyPasteContent属性设置为false是为了防止内容的复制/粘贴:
- 未设置密码:未设置密码的情况下,内容的复制/粘贴仍然被阻止。
- 用户密码设置:设置用户密码后,输入正确的密码将允许复制/粘贴内容。
- 所有者密码设置:设置所有者密码后,仅输入用户密码将无法解锁复制/粘贴功能。 但是输入正确的所有者密码将允许复制/粘贴内容。
相关文章讨论了预定义和自定义元数据。 通过点击以下链接了解更多信息:"如何设置和编辑 PDF 元数据."