2016-04-26 24 views
0

嗨,我有一個CGPDFDocument對象。我想通過在我的應用程序中顯示或使用外部應用程序來打開此文檔。這是我迄今爲止的代碼。如何在swift中顯示CGPDFDocument?

// 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) 

捆綁的PDF文檔的標題是「Newsletter.pdf」和「web視圖」是一個IBOutlet到:在SWIFT

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

您想從哪裏顯示?在你的主包(項目)中有你的pdf文件嗎? – Lion

回答

0

您可以輕鬆地由SWIFT使用下面的代碼顯示CGPDF文件一個UIWebView對象。

PDF文檔將很好地顯示,用戶將能夠滾動文檔,放大和縮小等等。

+1

你知道一種獲取cgPDFDocument文件名的方法嗎? –

4

與Objective-C中從this answer幫助,這裏是迅速的一個工作示例:

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

上面的代碼是你會被顯示在PDF視圖中drawRect方法只需添加這種觀點作爲你的viewController viewDidLoad方法中的子視圖,你就完成了。

+0

或者在視圖控制器的視圖中添加此自定義視圖。我遵循你的代碼,它運作良好。謝謝。 –

+0

太棒了。多謝這一點。在重構它(提供上下文,文件URL等作爲函數參數)之後,它可以很好地工作,並且可以用於根據正在使用的繪圖上下文的類型生成位圖圖像和矢量輸出(用於打印或PDF創建) 。 – Womble

相關問題