iOS PDFKit: make Text Widget PDFAnnotation readonl

2019-07-01 17:32发布

问题:

I would like to make the Text Widget PDFAnnotation readonly. I tried to set the isReadOnly flag to true, but it doesn't seem to make any difference. The user is still able to edit the annotation after tapping it.

回答1:

It seems to be a bug/oversight that PDFKit doesn't honor the isReadOnly attribute on annotations. However I was able to work around this by adding a blank annotation over other annotations in the document. I added a makeReadOnly() extension to PDF document that does this for all annotations to make the whole document read only. Here's the code:

// A blank annotation that does nothing except serve to block user input
class BlockInputAnnotation: PDFAnnotation {

    init(forBounds bounds: CGRect, withProperties properties: [AnyHashable : Any]?) {
        super.init(bounds: bounds, forType: PDFAnnotationSubtype.stamp,  withProperties: properties)
        self.fieldName = "blockInput"
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func draw(with box: PDFDisplayBox, in context: CGContext)   {
    }
}


extension PDFDocument {
    func makeReadOnly() {
        for pageNumber in 0..<self.pageCount {
            guard let page = self.page(at: pageNumber) else {
                continue
            }
            for annotation in page.annotations {
                annotation.isReadOnly = true // This _should_ be enough, but PDFKit doesn't recognize the isReadOnly attribute
                // So we add a blank annotation on top of the annotation, and it will capture touch/mouse events
                let blockAnnotation = BlockInputAnnotation(forBounds: annotation.bounds, withProperties: nil)
                blockAnnotation.isReadOnly = true
                page.addAnnotation(blockAnnotation)
            }
        }

    }
}