For over a week I have been trying to solve a printing issue in a macOS app I am writing using Swift and SwiftUI.
I need to print a view, which I have done by making it the main window but that does not work for the user. The data can come from a file or directly from user input so could be from 1 to 100 data sets.
Because I am printing the main window the application is unusable during the print process which is not acceptable.
The ideal solution would be to create the view off-screen then print the view. That way the user never sees it other than what comes out of the printer!
I have tried to find out how to print a view that is not the main window - no success, tried creating a second window managed to create the window but not print it!
No point in posting code as no idea which of the several ways I have tried could work, not even sure at this point if what I am trying to do is possible!
Please note this on Mac, not iPhone or iPad!
This worked for me, borrowed from the link in the comment from @Willeke . It involves converting to a bit map for printing.
let printInfo = NSPrintInfo()
let view = ContentView()
let contentRect = NSRect(x: 0, y: 0, width: 1080, height: 720) // these values will vary
let viewToPrint = NSHostingView(rootView: view)
viewToPrint.frame = contentRect
let bitMap = viewToPrint.bitmapImageRepForCachingDisplay(in: contentRect)!
viewToPrint.cacheDisplay(in: contentRect, to: bitMap)
let image = NSImage(size: bitMap.size)
image.addRepresentation(bitMap)
let imageView = NSImageView(frame: contentRect)
imageView.image = image
let printOperation = NSPrintOperation(view: imageView, printInfo: self.printInfo)
printOperation.showsPrintPanel = true
printOperation.showsProgressPanel = true
printOperation.run()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.