with help from this answer in objective-c, here is a working example in swift:
override func draw(_ rect: CGRect) {
super.draw(rect)
let context: CGContext = UIGraphicsGetCurrentContext()!
context.setFillColor(red: 1.0,green: 1.0,blue: 1.0,alpha: 1.0)
context.fill(self.bounds)
let filepath = (Bundle.main.path(forResource: "Example", ofType: "pdf"))! as String
let url = URL(fileURLWithPath: filepath)
let pdf: CGPDFDocument! = CGPDFDocument(url as CFURL)
let page: CGPDFPage = pdf.page(at: 1)!
let pageRect: CGRect = page.getBoxRect(CGPDFBox.mediaBox)
let scale: CGFloat = min(self.bounds.size.width / pageRect.size.width , self.bounds.size.height / pageRect.size.height)
context.saveGState()
context.translateBy(x: 0.0, y: self.bounds.size.height)
context.scaleBy(x: 1.0, y: -1.0)
context.scaleBy(x: scale, y: scale)
context.drawPDFPage(page)
context.restoreGState()
}
The above code is the drawRect
method for the view you will be displaying the pdf in. Just add this view as subview in your viewController viewDidLoad
method and you are done.