2016-01-20 34 views
1

我試圖創建一個斯威夫特簡單的命令行應用程序,將創建一個新的PDF,吸引到它,並且PDF保存到磁盤上一個新的PDF。下面是一個裸機版本的我的代碼:無法拉進與可可/雨燕/石英

// main.swift 
import Cocoa 

let fileName = "test.pdf" 

func getPath() -> NSURL? { 
    let fileManager = NSFileManager.defaultManager() 
    do { 
     let dir = try fileManager.URLForDirectory(
      NSSearchPathDirectory.DocumentDirectory, 
      inDomain: NSSearchPathDomainMask.UserDomainMask, 
      appropriateForURL: nil, 
      create: false 
     ) 
     return dir.URLByAppendingPathComponent(fileName) 
    } catch { 
     return nil 
    } 
} 

let context = CGPDFContextCreateWithURL(getPath(), nil, nil) 
CGPDFContextBeginPage(context, nil) 

let path = NSBezierPath(rect: NSRect(x: 0, y: 0, width: 100, height: 100)) 
NSColor.greenColor().set() 
path.fill() 

CGPDFContextEndPage(context) 
CGPDFContextClose(context) 

當運行這段代碼創建一個新test.pdf文件在我~/Documents目錄,符合市場預期,但它只是一個空白頁面8.5x11。任何繪圖代碼失敗,此錯誤:<Error>: CGContextSetFillColorWithColor: invalid context 0x0.

用於創建和拉絲成PDF,我可以找到的代碼示例都是很老。他們當然不是Swift,他們也傾向於使用Quartz C API,所以我現在感覺有點失落。

感謝您的閱讀。

+0

埃裏克,我偶然發現了這種需要就如何使分頁PDF的指南。您是否介意將您最終使用的代碼作爲下面的新答案發布?這對我非常有幫助! – owlswipe

+0

我正在寫一些文本到PDF上,分頁到字母大小的頁面。 – owlswipe

回答

1

你在這裏混合兩個世界。 CoreGraphics和高級Cocoa繪圖調用。爲了使可可繪圖工作,你需要根據一個CoreGraphics的創造互相轉換,使其成爲當前環境:

let graphicsContext = NSGraphicsContext(CGContext: context!, flipped:true) 
NSGraphicsContext.saveGraphicsState() 
NSGraphicsContext.setCurrentContext(graphicsContext) 
+0

非常感謝。也許我只是想讓蘋果公司的文檔正面或反面,但我不知道自己怎麼想到這一點。事實上,我甚至都沒有在Apple的文檔中看到'NSGraphicsContext(CGContext:flip:)'方法。代碼工作,方法在標題中,但不在文檔中。 ¯\ _(ツ)_ /¯ –

+0

的初始化不在文檔,這是事實。在目標C標頭,有'+(獲取到NSGraphicsContext *)graphicsContextWithCGContext:(CGContextRef)graphicsPort翻轉:(BOOL)initialFlippedState;'其轉換爲'獲取到NSGraphicsContext(CGContext上:翻轉:)'中夫特。 – fjoachim