SwiftUI view printout on paper

Hello and thanks for reading my post.

I have a SwiftUI view, the users should be able to click a button and take printout of that view. Clicking on the button should open the standard print sheet (select printer, pages, layout, etc.).

How can I implement such a functionality? I have been trying hard without any success. Please help.

It is an iPad app, using Xcode 14.3

I do it a bit differently.

Instead of calling directly the printer, I copy the view in the pasteboard. And I can then put in in any app (mail, preview…) and print if needed.

It is effectively a multi step process, but it provides interesting flexibility.

See complete solution here: https://developer.apple.com/forums/thread/730619

Hope that helps.

I showed for text, but it works as well for a complete view with subviews. Same principle, just change copyToClipboard:

    func copyToClipboard() {
        
        if let image = ViewForPaste() // The View to print
            .snapshot()?.png { 
            
            pasteboard.declareTypes([NSPasteboard.PasteboardType.png], owner: nil)
            pasteboard.setData(image, forType: .png)
            
        }
    }

But as I said, it is not the direct print you looked for.

For it, you need to use NSPrintOperation.

To print directly, have a look here on how to print an image:

https://stackoverflow.com/questions/71773747/how-to-print-a-swiftui-view-with-text-and-images-on-macos

then, use the snapshot created for the pasteborad

Claude31. did you ever get this to work? I followed devlabs and got the text to print they showed but am having same issue as you. printing a portion of my screen.

Got it working. I wrapped my SwiftUI View to be printed(and displayed) in a local function like this:

private func generateView() -> some View {
    VStack { .... }
}

Then I created a func to save the some View as a PDF in the document directory using ImageRenderer. The func also returns the PDF's URL which was created using URL.documentsDirectory.appending(path:)

Then I created another func using UIPrintInteractionController and the PDF's URL to present the print controller for the saved pdf.

SwiftUI view printout on paper
 
 
Q