How to display CGPDFDocument in swift?

ε祈祈猫儿з 提交于 2019-12-03 21:55:40
Nilo0f4r

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!