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

时间:2017-02-25 22:22:09

标签: ios swift pdf

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

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

我在GitHub上发现了一个叫做“UXMPDF”的cocoapod。有没有人用过这个?

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

1 个答案:

答案 0 :(得分:2)

首先创建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))

    }

您可以像这样从UIMenuItem使用pdfAnnotation:

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

您可以使用的其他pdfAnnotation:

.underline
.strikeOut
.circle
.square

enter image description here