在 iText7 中管理 PDF 使用权限

问题描述

我在 iTextSharp v5 中使用 PdfReader.HasUsageRights()PdfReader.RemoveUsageRights()。在 iText7 中似乎找不到类似的功能

解决方法

可能没有直接的替代方法,但您自己实现这些方法很容易:

public boolean hasUsageRights(PdfDocument pdfDocument) {
    PdfDictionary perms = pdfDocument.getCatalog().getPdfObject().getAsDictionary(PdfName.Perms);
    if (perms == null) {
        return false;
    }
    return perms.containsKey(new PdfName("UR")) || perms.containsKey(PdfName.UR3);
}

public void removeUsageRights(PdfDocument pdfDocument) {
    PdfDictionary perms = pdfDocument.getCatalog().getPdfObject().getAsDictionary(PdfName.Perms);
    if (perms == null) {
        return;
    }
    perms.remove(new PdfName("UR"));
    perms.remove(PdfName.UR3);
    if (perms.size() == 0) {
        pdfDocument.getCatalog().remove(PdfName.Perms);
    }
}

如果您需要第一种方法,那么您可以传递使用 PdfDocument(PdfReader,PdfWriter) 构造函数或 PdfDocument(PdfReader) 创建的文档。如果您需要第二种方法,那么您需要传递以戳记模式创建的文档,即使用 PdfDocument(PdfReader,PdfWriter) 构造函数