0

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)
Jurian Amatsahip
  • 187
  • 1
  • 2
  • 11

2 Answers2

7

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.

Community
  • 1
  • 1
Nilo0f4r
  • 168
  • 2
  • 12
  • Or add this custom view in the view of view controller, in storyboard. I followed your code and it works well. Thank you. – Homer Wang Oct 02 '16 at 16:04
  • Awesome. Thanks a bunch for this. After refactoring it out (provide context, file URL etc. as function arguments), this works beautifully, and can be used to generate both bitmap images and vector output (for printing or PDF creation) depending on what type of drawing context is being used. – Womble Mar 01 '17 at 00:13
0

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.

Abhinandan Pratap
  • 2,142
  • 1
  • 18
  • 39