Search code examples
itextitext7

Managing PDF usage rights in iText7


I'm using PdfReader.HasUsageRights() and PdfReader.RemoveUsageRights() in iTextSharp v5. Can't seem to find similar functionality in iText7?


Solution

  • There is probably no direct alternative but it's easy to implement those methods yourself:

    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);
        }
    }
    

    If you need the first method then you can pass either a document created with PdfDocument(PdfReader, PdfWriter) constructor or with PdfDocument(PdfReader) one. If you need the second method then you need to pass a document created in stamping mode, i.e. with PdfDocument(PdfReader, PdfWriter) constructor