如何在swift中显示CGPDFDocument? [英] How to display CGPDFDocument in swift?

查看:729
本文介绍了如何在swift中显示CGPDFDocument?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我有一个CGPDFDocument对象。我想通过在我的应用程序中显示它或使用外部应用程序来打开此文档。这是我到目前为止的代码。在SWIFT中

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)


推荐答案

在objective-c的此答案的帮助下,这是一个有效的工作swift中的示例:

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()
}

以上代码是您将要显示的视图的 drawRect 方法pdf in。只需在viewController viewDidLoad 方法中将此视图添加为子视图,即可完成。

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.

这篇关于如何在swift中显示CGPDFDocument?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆