PDFNet is easy to use with a Swift project. This post will show how to set up a new Swift project and display a PDF.
This post will show you the basics of starting a new Swift project that uses PDFNet. For a comprehensive introduction to PDFNet on iOS, please see Getting Started on iOS. A completed Swift sample project is included with the most recent version of PDFNet for iOS.
1. Open Xcode 8+, and select File->New Project->Single View Application. Create a new Universal Swift app.
2. Add the following PDFNet files to your project:
- Lib/Framework-dynamic/PDFNet.framework
- Lib/Tools/Tools.framework
- TestFiles/mech.pdf
3. Link in the following Apple frameworks
- MediaPlayer.framework
- CoreText.framework
- CoreMedia.framework
4. In the file ViewController.swift, change the viewDidLoad() function to the following:
import UIKit
import PDFNet
import Tools
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// initialize PDFNet
PTPDFNet.initialize("")
// create a PTPDFViewCtrl and add it to the view
let ctrl = PTPDFViewCtrl()
ctrl.frame = CGRect(origin: CGPoint.zero, size: self.view.bounds.size)
ctrl.setBackgroundColor(0, g: 0, b: 0, a: 0)
self.view.backgroundColor = UIColor.init(colorLiteralRed:0.7, green:0.7, blue:0.7, alpha: 1.0)
self.view.addSubview(ctrl)
// open the PDF document included in the bundle in the PTPDFViewCtrl
let docPath = Bundle.main.path(forResource: "mech", ofType: "pdf")
let doc = PTPDFDoc(filepath: docPath!)
ctrl.setDoc(doc)
ctrl.autoresizingMask = [.flexibleWidth, .flexibleHeight];
// add the toolmanager (used to implement text selection, annotation editing, etc.
let toolManager = ToolManager(pdfViewCtrl: ctrl)
ctrl.toolDelegate = toolManager;
_ = toolManager?.changeTool(PanTool.self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
If you run the project, the program should now display the PDF mech.pdf. As stated above, a completed version of this sample is available in the latest version of PDFNet, so please check it out!