在Swift中对PDF进行注释/绘制

evo*_*g88 7 pdf ios swift

我正在编写一个包含多个PDF文档的应用程序,我将根据用户的输入显示在屏幕上.一旦显示,我想允许用户在PDF上绘制/注释.然后我想保存带有图纸/注释的PDF以供以后使用.

我已经无休止地搜索了关于注释PDF的教程,但我回来的时间并不多!

我在GitHub上发现了一个名为'UXMPDF'的cocoapod.有没有人用过这个?

有关执行此类操作的任何信息都将非常感谢!谢谢

Zou*_*ssi 4

首先创建 PDFView 并加载 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))

    }
Run Code Online (Sandbox Code Playgroud)

您可以像这样使用 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)
        })
     }
   }
Run Code Online (Sandbox Code Playgroud)

如果你想保存你所做的事情:

self.pdfView.document.write(to:YOUR_FILE_URL)
Run Code Online (Sandbox Code Playgroud)

您可以使用其他 pdfAnnotation:

.underline
.strikeOut
.circle
.square
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述