Saturday, July 7, 2018

Adventures in PDF Swift and PDFKit

Adventures in PDF Swift and PDFKit



Working with PDFs in OS X is straightforward using PDFKit.

PDFDocument

It all starts with the PDFDocument class and in order to leverage this you simply import Quartz and get started. Like so:
import Quartz

let url = NSBundle.mainBundle().URLForResource("myPDF", withExtension: "pdf")
let pdf = PDFDocument(URL: url)
pdf.pageCount() // number of pages in document
pdf.string() // entire text of document
As you can see counting the number of pages and accessing the text is straightforward and theres plenty more to explore alongside this, but I want to move quickly along to working with pages.

PDFPage

While you can access a string of the entire document and this is useful for searches, more often youll want to work with PDFPage instances. You access pages by their index:
import Quartz

let url = NSBundle.mainBundle().URLForResource("myPDF", withExtension: "pdf")
let pdf = PDFDocument(URL: url)
let page = pdf.pageAtIndex(10) // returns a PDFPage instance
page.attributedString() // attributed string for the PDFPage instance

You could convert an entire PDF to a single NSAttributedString:
import Quartz

let url = NSBundle.mainBundle().URLForResource("myPDF", withExtension: "pdf")
let pdf = PDFDocument(URL: url)
let docStr = NSMutableAttributedString()
for i in 0..<pdf.pageCount() {
docStr.appendAttributedString(doc.pageAtIndex(i).attributedString())
}

but this would take a good deal of time for a long PDF and if you are looking to simply display the PDF then PDFView is the class youre looking for.

PDFView

Creating a PDFView is once again a straightforward thing to do:
import Quartz

let url = NSBundle.mainBundle().URLForResource("myPDF", withExtension: "pdf")
let pdf = PDFDocument(URL: url)
let view = PDFView(frame: CGRect(x: 0, y: 0, width: 500, height: 750))
view.setDocument(pdf)

PDF Extras

Beyond the document, page and view classes there are PDFOutline, PDFSelection, and PDFAnnotation. The latter being a superclass of twelve further classes. Completing the PDFKit classes theres also PDFBorder, which is used for adding decoration to annotations.

To explore in depth read through the PDFKit Programming Guide.

Follow @sketchytech
Endorse on Coderwall


visit link download