evorg88
evorg88

Reputation: 215

Annotate/Draw on PDF in Swift

I am writing an app that will contain multiple PDF documents that I will display on screen depending on the user's input. Once displayed, I would like to allow the user to draw/annotate on the PDF. I would then like to save the PDF with the drawings/annotations on for later use.

I have searched endlessly for tutorials on annotating a PDF but I am coming back with not much at all!

I have found a cocoapod on GitHub called 'UXMPDF'. Has anyone used this?

Any information on performing this type of operation would be hugely appreciated! Thanks

Upvotes: 8

Views: 4344

Answers (1)

Zouhair Sassi
Zouhair Sassi

Reputation: 1411

First Create PDFView and Load pdfFile:

override func viewDidLoad() {
super.viewDidLoad()    
let pdfView = PDFView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height))
        guard let document = PDFDocument(url: YOUR_FILE_PATH) else {
            return
        }
        pdfView.document = document
        pdfView.displayMode = .singlePageContinuous
        pdfView.autoScales = true
        pdfView.displayDirection = .horizontal
        pdfView.autoresizingMask = [.flexibleWidth, .flexibleHeight, .flexibleTopMargin, .flexibleBottomMargin]
        pdfView.maxScaleFactor = 4
        pdfView.delegate = self
        pdfView.minScaleFactor = pdfView.scaleFactorForSizeToFit
        pdfView.usePageViewController(true, withViewOptions: nil)
        pdfView.translatesAutoresizingMaskIntoConstraints = false
        self.view.addSubview(pdfView)
        self.pdfView = pdfView
        self.pdfDocument = document
        let highLightItem = UIMenuItem(title:"Highlight"), action: #selector(highlightFromMenuItem))

    }

you can use pdfAnnotation from UIMenuItem like that:

@objc func highlightFromMenuItem() {
 if let document = self.pdfDocument {
    let pdfSelection : PDFSelection = PDFSelection(document: document)
    pdfSelection.add((self.pdfView?.currentSelection)!)
    let arrayByLines = self.pdfView?.currentSelection?.selectionsByLine()
        arrayByLines?.forEach({ (selection) in
            let annotation = PDFAnnotation(bounds: selection.bounds(for: (self.pdfView?.currentPage)!), forType: .highlight, withProperties: nil)
            annotation.color = .yellow
            self.pdfView?.currentPage?.addAnnotation(annotation)
        })
     }
   }

If you want to save what did you did:

self.pdfView.document.write(to:YOUR_FILE_URL)

other pdfAnnotation you can use:

.underline
.strikeOut
.circle
.square

enter image description here

Upvotes: 4

Related Questions