0
votes

I have a multi-page document, and I use a A4 sized NSView to display a single page (one at a time). I use a “forward/backward” button to control the page selection. So each time the button is pressed, the correct page is re-drawn in the NSView. The drawings are simple, so it is not too bad.

But I don’t know how I can generate a multi page PDF document to include all my pages. Someone gave me some code to convert the content of NSView to PDF, I am using that code to generate single page PDFs, but I really like to draw all pages into a single PDF.

Can someone tell me how to modify the following code to do this? Many thanks.

//////

     var fn: String = fnBase

    for i in 0...TotalPage - 1 {

        // This will tell DrawRect to draw page i
        view.displayedPage = i

        let bounds = CGRect(origin: CGPointZero, size: view.frame.size)
        let data: NSData = view.dataWithPDFInsideRect(bounds)

        fn = fnBase + "\(i+1).pdf"

        data.writeToFile(fn, atomically: true)
    }
1

1 Answers

2
votes

My Solution:

import Quartz

var data = documentView.dataWithPDF(inside: NSMakeRect(0.0, 0.0, width, height))
let pdfDocument = PDFDocument(data: data)!

for i in 1..<pages {
    data = documentView.dataWithPDF(inside: NSMakeRect(0.0, CGFloat(i) * height, width, height))
    let pdfPage = PDFPage(image: NSImage(data: data)!)!
    pdfDocument.insert(pdfPage, at: pdfDocument.pageCount)
}