Create a paginated PDF with Swift and Cocoa

I am making a Mac app in Swift 3 with which the user can make a long note and export it as a PDF.

To create this PDF, I am using Cocoa's

dataWithPDF:
method with the following code:
do {
       // define bounds of PDF as the note text view
       let rect: NSRect = self.noteTextView.bounds
       // create the file path for the PDF
       if let dir = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true).first {
            // add the note title to path
            let path = NSURL(fileURLWithPath: dir).appendingPathComponent("ExportedNote.pdf")
            // Create a PDF of the noteTextView and write it to the created filepath
            try self.noteTextView.dataWithPDF(inside: rect).write(to: path!) 
       } else {
            print("Path format incorrect.") // never happens to me
       }
           
    } catch _ {
        print("something went wrong.") // never happens to me
    }

This completely works, but there's one problem: the PDF goes only on one page, which means the single page gets really (infinitely) long when there's a lot of text in the note. How can I force the PDF to go onto as many letter-size pages as it needs, either while my app is exporting the PDF or right after?


I need this in Swift, not Objective-C

Totally figured this out myself. See the Stack Overflow guide here: http://stackoverflow.com/questions/38947782/how-to-create-a-pdf-in-swift-with-cocoa-mac/39479222#39479222

Create a paginated PDF with Swift and Cocoa
 
 
Q