Annotate / draw PDF in Swift

I am writing an application that will contain several PDF documents that will be displayed on the screen depending on user input. After displaying, I would like to allow the user to draw / annotate in PDF. Then I would like to save the PDF with drawings / annotations for later use.

I have endlessly searched for tutorials on annotating a PDF document, but I am not returning at all so much!

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

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

+7
source share
1 answer

First create a PDFView and download 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))

    }

pdfAnnotation UIMenuItem :

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

, :

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

pdf , :

.underline
.strikeOut
.circle
.square

enter image description here

+2

Source: https://habr.com/ru/post/1670843/


All Articles