Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To include the background when printing from WKWebView in Swift, you can set the CSS property background-color to transparent for the body element of the HTML document that you are printing.

You can do this by injecting JavaScript code into the WKWebView's page using the evaluateJavaScript method. Here's an example:

let printController = UIPrintInteractionController.shared

guard let printFormatter = webView.viewPrintFormatter() else { return }

// Set CSS to show background color
let bgColorScript = "document.body.style.backgroundColor = 'transparent'"
webView.evaluateJavaScript(bgColorScript, completionHandler: nil)

printController.printFormatter = printFormatter
printController.present(animated: true, completionHandler: nil)

The bgColorScript variable sets the background-color CSS property to transparent for the body element of the HTML document. This causes the WKWebView to include the background in the printed output.

After injecting the script, we create a print formatter from the WKWebView using the viewPrintFormatter method. We then set this print formatter in the printController, which we use to present the print interface.