Is there any documentation or advice on printing from a Safari webapp (in JavaScript)? My app needs to print labels, and printing from Safari presents few options.
For example, you can't turn off backgrounds or the URL/date/time footer. And it wants to print a full-size page, which ends up printing miles of label.
(I've also tried printing from SwiftUI on a macOS app, and even that is just terrible to try to get right. Why is printing so hard?)
In my tests, CSS controlled the label's layout, the header and footer, and the background. The paper size came from the print dialog. I tested in Safari 27.0.1 in macOS 27.0.1, saving each printout as a PDF from the print dialog.
The rule @page { size: 4in 2in; margin: 0; } lays the page out at label size, but it doesn't change the paper. With the Paper Size set to US Letter, the label printed at the top left of a Letter page. With a custom 4 x 2 inch paper size chosen in the print dialog, the same page printed as one label-sized page. So the person printing has to choose the label size as the paper size in the print dialog. Safari 18.2 added support for the @page margin descriptors.
With "Print headers and footers" checked, Safari added a header and footer to a page with no @page rule. They showed the page title, the date and time, the URL, and the page number. With @page { margin: 0; }, it added none of them, with the option still checked. That's what Safari 27.0.1 did. It isn't documented. Put any space you want around the label in the label's own padding.
A print style removed the label's background color:
@media print {
.label { background: none; }
}
The window.print() method opens the print dialog. I don't know of a way for a webpage to choose the printer or the paper, or to print without the dialog.
If you need that control, an app that shows your page in a WKWebView can print it itself. Your JavaScript can ask the app to print through a WKScriptMessageHandler. In macOS, I printed the same page with printOperation(with:). I gave it an NSPrintInfo with a 4 x 2 inch paperSize and zero margins, and got one 4 x 2 inch page per label. In iOS and iPadOS, the web view's viewPrintFormatter() works with UIPrintInteractionController, whose delegate can choose label-sized paper in printInteractionController(_:choosePaper:).