Swift Cannot print from NSView "CGContextGetCTM: invalid context 0x0"

194 views Asked by At

I'm making a macOS app at the moment, and I'm trying to support printing. I've added NSBox to represent the pages I want to print inside an NSScrollView, so the hierarchy looks like this

NSScrollView
|- NSDocumentView
   |- NSBox
   |- NSBox

Print Preview

In the ViewController, when the user clicks on print, I run the following code

let printOperation = NSPrintOperation(view: self.previewView, printInfo: printInfo)

if let window = self.view.window {
    printOperation.runModal(for: window, delegate: self, didRun: #selector(PrintPreviewViewController.printOperationDidRun(_:success:contextInfo:)), contextInfo: nil)
}

In the NSDocumentView subclass, I've implemented

override func knowsPageRange(_ range: NSRangePointer) -> Bool {

    var numberOfPages = 0

    for i in 0..<pages.count {
        numberOfPages += pages[i].count
    }

    range.pointee.location = 1
    range.pointee.length = numberOfPages

    return true
}

override func rectForPage(_ page: Int) -> NSRect {

    var pageNumber = 1

    for i in 0..<pages.count {
        for j in 0..<pages[i].count {

            if pageNumber == page {
                return pages[i][j].frame
            }
            pageNumber += 1
        }
    }

    return NSRect(x: 0, y: 0, width: 300, height: 300)

}

When I run, I see the print sheet that all looks correct.

Print sheet

But when I finally confirm print, I get these errors in the console, and a blank sheet.

CGContextGetCTM: invalid context 0x0
CGContextTranslateCTM: invalid context 0x0

I don't know what this means, as everything is displayed correctly inside the NSScrollView, and even the print preview. I tried to narrow down the issue, I tried making a blank project with just one NSBox inside an NSScrollView, and I was having the same issue. I tried changing the size of NSRect bering returned in rectForPage(), but nothing works. I'm out of ideas.

Thank you all in advance.

0

There are 0 answers