iosswiftpdfcgpdfcontext

PDF is blank page when using CGPDFContextCreateWithURL


I'm trying to create a simple pdf with CGPDFContextCreateWithURL, but when I show the pdf it's blank. My code:

 override func viewDidLoad() {
    super.viewDidLoad()

drawSuperPDF("test4.pdf")

   showPDFFile()

}

My drawSuperPDF() function

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)


}

My drawHeaders() and drawHeaderText() functions

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

}

And finally, my 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)


}

Solution

  • Before you start drawing on a PDF page, you need to "start" the page by calling CGPDFContextBeginPage. Calls to begin page and end page need to be balanced out by the way.