使用 CGPDFContextCreateWithURL 时 PDF 为空白页

PDF is blank page when using CGPDFContextCreateWithURL

我正在尝试使用 CGPDFContextCreateWithURL 创建一个简单的 pdf,但是当我显示 pdf 时它是空白的。我的代码:

 override func viewDidLoad() {
    super.viewDidLoad()

drawSuperPDF("test4.pdf")

   showPDFFile()

}

我的 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)


}

开始在 PDF 页面上绘图之前,您需要通过调用 CGPDFContextBeginPage 来 "start" 页面。顺便平衡一下开始页和结束页的调用。