Search code examples
pdfannotationsios11

how to add image annotation in PDFKit in iOS11


I am using PDFKit in iOS11 to develop a app which can show pdf file add annotations. Now I want to add an image annotation to the pdf page, I think the annotation subtype should be stamp. But in PDFKit I cannot find the property like "image" to set, the only property related to stamp annotation is stampName. Can anyone help?


Solution

  • Here's how I managed to do it. The idea is to override the draw() function to do the bidding of the now absent PDFAnnotationStamp class (I found some obsolete doc about different kind of PDFAnnotation subclasses that are now gone). This problem doesn't seem to be recent, and the dev boards are really empty iOS side, it's almost scary.

    public class ImageAnnotation: PDFAnnotation {
    
        private var _image: UIImage?
    
        public init(imageBounds: CGRect, image: UIImage?) {
            self._image = image
            super.init(bounds: imageBounds, forType: .stamp, withProperties: nil)
        }
    
        required public init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
        override public func draw(with box: PDFDisplayBox, in context: CGContext) {
            guard let cgImage = self._image?.cgImage else {
                return
            }
           let drawingBox = self.page?.bounds(for: box)
           //Virtually changing reference frame since the context is agnostic of them. Necessary hack.
           context.draw(cgImage, in: self.bounds.applying(CGAffineTransform(
           translationX: (drawingBox?.origin.x)! * -1.0, 
                      y: (drawingBox?.origin.y)! * -1.0)))
        }
    
    }