访问权限不起作用

时间:2015-09-04 05:19:41

标签: java pdfbox

我一直试图对我的pdf进行许可。     我有一个方法,它将在一个名为access

的实例变量上设置访问权限
 private AccessPermission access = new AccessPermission();
    public void setPdfPermissions(boolean allowPrint, boolean degradePrint,
                boolean editPage, boolean allowAssembly, boolean allowCopy,
                boolean allowReaders, boolean editAnnotation, boolean allowFillIn) {
            if (allowPrint) { // allow printing
                access.setCanPrint(allowPrint);
            }
            if (degradePrint) { // degrade printing
                access.setCanPrintDegraded(allowAssembly);
            }
            if (editPage) { // edit page contents
                access.setCanModify(editPage);
            }
            if (allowAssembly) { // insert, remote or rotate page
                access.setCanAssembleDocument(allowAssembly);
            }
            if (allowCopy) { // copy page contents or graphics
                access.setCanExtractForAccessibility(allowCopy);
            }
            if (allowReaders) { // screen readers can copy contents or graphics
                access.setReadOnly();
            }
            if (editAnnotation) { // edit annotations
                access.setCanModifyAnnotations(editAnnotation);
            }
            if (allowFillIn) { // fill form fields
                access.setCanFillInForm(allowFillIn);
            }

        }

然后我在安全处理程序中保存访问权限

StandardSecurityHandler secHandler = new StandardSecurityHandler();
             if((userPass != null) || (ownerPass != null)) {
                 System.out.println("userPass:"+userPass+"owner pass:"+userPass);
                // TODO
                StandardProtectionPolicy policy = new StandardProtectionPolicy(ownerPass.toString(), userPass.toString(),
                      access);
                secHandler = new StandardSecurityHandler(policy);
  document.setSecHandler(secHandler);

当我将setPrint之类的值传递为false时,它允许我打印。任何帮助都非常感谢。

2 个答案:

答案 0 :(得分:1)

您的第二个代码块错误。 {(3}}描述了加密文件的正确方法(至少对1.8版本而言)。所以对你来说,正确的代码是:

// owner password to open the file with all permissions
// user password to open the file but with restricted permissions, can be empty 
StandardProtectionPolicy spp = new StandardProtectionPolicy(ownerPass, userPass, access);
spp.setEncryptionKeyLength(128);
doc.protect(spp);

编辑:另请参阅mkl的答案,为什么您的第一个代码段也是错误的: - )

答案 1 :(得分:1)

除了@Tilman的回答,第一个代码块也是错误的:

对于每个boolean参数,setPdfPermissions仅在值为true时执行某些操作,例如:

if (allowPrint) { // allow printing
    access.setCanPrint(allowPrint);
}

如果默认情况下未授予权限,这将有效。但是,查看AccessPermission默认构造函数的定义,可以看到相反的情况,例如在1.8.10的代码中:

/**
 * Create a new access permission object.
 * By default, all permissions are granted.
 */
public AccessPermission()
{
    bytes = DEFAULT_PERMISSIONS;
}

因此,setPdfPermissions本质是一个很大的NOP(无操作)代码块。

相关问题