设置 PDF 权限

在现有 PDF 文件上设置权限

要设置 PDF 文件的权限,请创建一个 PdfFileSecurity 对象并调用 SetPrivilege 方法。您可以使用 DocumentPrivilege 对象指定权限,然后将此对象传递给 SetPrivilege 方法。以下代码片段演示了如何设置 PDF 文件的权限。

// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void SetPrivilege1()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_SecuritySignatures();
    
    // Create DocumentPrivileges object and set needed privileges
    var privilege = Aspose.Pdf.Facades.DocumentPrivilege.ForbidAll;
    privilege.ChangeAllowLevel = 1;
    privilege.AllowPrint = true;
    privilege.AllowCopy = true;

    using (var fileSecurity = new Aspose.Pdf.Facades.PdfFileSecurity())
    {
        // Bind PDF document
        fileSecurity.BindPdf(dataDir + "sample.pdf");
        // Set privilege
        fileSecurity.SetPrivilege(privilege);
        // Save PDF document
        fileSecurity.Save(dataDir + "SamplePrivileges_out.pdf");
    }
}

请参见以下方法并指定密码:

// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void SetPrivilegeWithPassword()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_SecuritySignatures();
    
    // Create DocumentPrivileges object and set needed privileges
    var privilege = Aspose.Pdf.Facades.DocumentPrivilege.ForbidAll;
    privilege.ChangeAllowLevel = 1;
    privilege.AllowPrint = true;
    privilege.AllowCopy = true;

    using (var fileSecurity = new Aspose.Pdf.Facades.PdfFileSecurity())
    {
        // Bind PDF document
        fileSecurity.BindPdf(dataDir + "sample.pdf");
        // Set privilege and passwords
        fileSecurity.SetPrivilege(string.Empty, "P@ssw0rd", privilege);
        // Save PDF document
        fileSecurity.Save(dataDir + "SamplePrivilegesPassword_out.pdf");
    }
}

从 PDF 中移除扩展权限功能

PDF 文档支持扩展权限功能,以便最终用户使用 Adobe Acrobat Reader 填写表单字段,然后保存填写后的表单副本。然而,它确保 PDF 文件未被修改,如果对 PDF 的结构进行任何修改,扩展权限功能将丢失。查看此类文档时,会显示错误消息,指出由于文档已被修改,扩展权限已被移除。最近,我们收到了一个要求,从 PDF 文档中移除扩展权限。

要从 PDF 文件中移除扩展权限,PdfFileSignature 类中添加了一个名为 RemoveUsageRights() 的新方法。另一个名为 ContainsUsageRights() 的方法被添加以确定源 PDF 是否包含扩展权限。

以下代码演示了如何从文档中移除使用权限:

// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void RemoveExtendedRights()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdfFacades_SecuritySignatures();
    
    using (var pdfSign = new Aspose.Pdf.Facades.PdfFileSignature())
    {
        // Bind PDF document
        pdfSign.BindPdf(dataDir + "DigitallySign.pdf");
        if (pdfSign.ContainsUsageRights())
        {
            pdfSign.RemoveUsageRights();
        }
        // Save PDF document
        pdfSign.Document.Save(dataDir + "RemoveRights_out.pdf");
    }
}