问题
I have had a problem with printing a certificate with a background image and overlay text.
My solution after much research is to convert a view to an image and print that and it works UNLESS the print dialogue is canceled then get a crash.
I have tried many versions of the code, even a test app that only does the print function and always get the crash on canceling print. If the certificate is printed no apparent issues.
following in one of many versions of the code I have tried, all with the same result on cancel.
App is Mac desktop, SwiftUi latest everything.
let contentView = ContentView()
let contentRect = NSRect(x: 0, y: 0, width: 620, height: 860)
let newWindow = NSWindow(
contentRect: contentRect,
styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
backing: .buffered, defer: false)
newWindow.contentView = NSHostingView(rootView: contentView)
let myNSBitMapRep = newWindow.contentView!.bitmapImageRepForCachingDisplay(in: contentRect)!
newWindow.contentView!.cacheDisplay(in: contentRect, to: myNSBitMapRep)
let myNSImage = NSImage(size: myNSBitMapRep.size)
myNSImage.addRepresentation(myNSBitMapRep)
var printView = NSImageView(frame: NSRect(x: 0, y: 0, width: 620, height: 860))
printView.image = myNSImage
let printInfo = NSPrintInfo()
printInfo.horizontalPagination = .fit
printInfo.verticalPagination = .automatic
printInfo.leftMargin = 0.0
printInfo.rightMargin = 0.0
printInfo.topMargin = 0.0
printInfo.bottomMargin = 0.0
let paperBounds = printInfo.imageablePageBounds
let origin = paperBounds.origin
let size = paperBounds.size
print( "Origin X:\(origin.x), y:\(origin.y) - Size width:\(size.width), height:\(size.height)")
let printOperation = NSPrintOperation(view: printView, printInfo: printInfo)
printOperation.showsPrintPanel = true
printOperation.showsProgressPanel = true
printOperation.canSpawnSeparateThread = true
printOperation.run()
来源:https://stackoverflow.com/questions/62593232/canceling-print-operating-crashes-swift-mac-desktop-app