2016-03-04 125 views
0

我想用CGPDFContextCreateWithURL创建一个简单的pdf,但是当我显示PDF时它是空白的。我的代码:使用CGPDFContextCreateWithURL时PDF是空白页

我drawSuperPDF()函数

func drawSuperPDF(filename: String) { 

    let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] 
    let pdfFileName = documentsURL.URLByAppendingPathComponent(filename) 
    let fullPath = pdfFileName.path! 

    let url = NSURL(fileURLWithPath: fullPath) 


    var mediaBox:CGRect = CGRectMake(0, 0, 612, 792) 


    let myPDFContext = CGPDFContextCreateWithURL(url, &mediaBox, nil) 


    drawHeaders() 



CGPDFContextEndPage(myPDFContext) 


} 

我drawHeaders()和drawHeaderText()函数

func drawHeaders() { 


    drawHeaderText(CGPoint(x: 30, y: 10), headerText: "Hello World:", underline: true) 


    drawHeaderText(CGPoint(x: 30, y: 25), headerText: "Hello World:", underline: true) 


    drawHeaderText(CGPoint(x: 30, y: 40), headerText: "Hello World:", underline: true) 


    drawHeaderText(CGPoint(x: 30, y: 70), headerText: "Hello World:", underline: true) 




} 

func drawHeaderText(point: CGPoint, headerText: String, underline: Bool) { 

    let drawingPoint = CGPoint(x: point.x, y: point.y) 

    if underline { 


     var multipleAttributes = [String : NSObject]() 
     multipleAttributes[NSFontAttributeName] = UIFont.boldSystemFontOfSize(12) 
     multipleAttributes[NSUnderlineStyleAttributeName] = NSUnderlineStyle.StyleSingle.rawValue 


     headerText.drawAtPoint(drawingPoint, 
      withAttributes: multipleAttributes) 


    } else { 

     let font = UIFont.systemFontOfSize(12) 
     headerText.drawAtPoint(drawingPoint, 
      withAttributes: [NSFontAttributeName : font])} 

} 

最后,我showPDFFile()

func showPDFFile() { 

    let fileName = "test4.pdf" 
    let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] 
    let pdfFileName = documentsURL.URLByAppendingPathComponent(fileName) 
    let fullPath = pdfFileName.path! 
    let webView : UIWebView = UIWebView(frame: CGRectMake(0, 0, self.view.frame.width, self.view.frame.height)) 
    let url : NSURL = NSURL(fileURLWithPath: fullPath) 
    let request : NSURLRequest = NSURLRequest(URL: url) 

    webView.scalesPageToFit = true 
    webView.loadRequest(request) 

    self.view.addSubview(webView) 


} 
+0

您正在调用“CGPDFContextEndPage”,但不是BeginPage调用。如果在开始绘制页面之前没有必要,我会很惊讶。 –

+0

感谢David,我添加了CGPDFContextBeginPage(myPDFContext,零) ,现在我可以使用核心图形绘制简单的图形,但无法绘制文本 - 非常令人沮丧。 – Tom

+0

:)不能拥有一切。我会把它写成答案。请批准它为正确的,并提出一个新的问题的文字,可能是你做错了文本调用,但应该很容易发现。 –

回答

0

在开始绘制PDF之前页面,您需要通过呼叫CGPDFContextBeginPage“启动”该页面。呼吁开始页面和结束页面需要平衡的方式。