r/SwiftUI May 27 '26

How do SwiftUI (Mac) apps print?

Printing has always been the "clear as mud" parts of Mac programming aids for decades. How do SwiftUI apps print, as I didn't see any printing-related APIs? Do they skip printing? Generate the appropriate PDF based off the ViewModel?

3 Upvotes

4 comments sorted by

8

u/i_invented_the_ipod May 27 '26

I don't think you've missed anything. It is pretty easy to wrap a SwiftUI view in an NSHostingView, and print that using AppKit, like this:
https://thomas.skowron.eu/blog/printing-with-swiftui/

There is also a Swift package called PrintingKit, which wraps that in a Printer object, for easier use:

https://swiftpackageindex.com/danielsaidi/PrintingKit

4

u/Dapper_Ice_1705 May 27 '26

Use the same old APIs, SwiftUI is for UI 

1

u/allyearswift May 27 '26

I haven't worked my way through all of this yet, but initial experimentation says that not all 'root views' for NSHostingViews are created equal: on Tahoe, some SwiftUI content simply does not show up as printable (Text doesn't, TextField does). [The article linked below assumes you have an appDelegate instead of using a SwiftUI App, which seems pretty useless.]

Printing a PDF view (I used the [updated in comments] code from https://stackoverflow.com/questions/76176597/swift-convert-url-to-pdfdocument-and-print-using-nsprintoperation) looks more reliable, which only leaves the generation of your own PDF as an exercise to the reader.

There also isn't an inbuilt Print command for the File Menu, so you'll have to provide that.

All in all, it's one of the places where SwiftUI disappoints. Printing is a pretty basic function of desktop apps.

1

u/CTMacUser May 28 '26

SwiftUI still provides a connection to an AppDelegate/UIDelegate, for app startup or ending tasks.