How to display CGPDFDocument in swift?

5.8k Views Asked by At

Hi I have a CGPDFDocument object. I want to open this document by either showing it in my app or using an external application. Here is the code I have so far. in SWIFT

 let cfData = CFDataCreate(kCFAllocatorDefault, UnsafePointer<UInt8>(data.File.bytes), data.File.length)
 let cgDataProvider =  CGDataProviderCreateWithCFData(cfData)
 let cgPDFDocument  =  CGPDFDocumentCreateWithProvider(cgDataProvider)
2

There are 2 best solutions below

1
Abhinandan Pratap On

You can easily display CGPDF document in swift by using the following code:

// Get the document's file path.
let path = NSBundle.mainBundle().pathForResource("Newsletter.pdf", ofType: nil)

// Create an NSURL object based on the file path.
let url = NSURL.fileURLWithPath(path!)

// Create an NSURLRequest object.
let request = NSURLRequest(URL: url)

// Load the web viewer using the request object.
webView.loadRequest(request)

the bundled PDF document is titled "Newsletter.pdf," and "webView" is an IBOutlet to a UIWebView object.

The PDF document will display nicely, and users will be able to scroll through the document, zoom in and out, and so on.

2
Nilo0f4r On

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.