Ask Your Question

When printing from WKWebView in Swift, the background is not taken into account.

asked 2022-11-01 11:00:00 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2022-08-06 14:00:00 +0000

nofretete gravatar image

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 = " = '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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer

Question Tools


Asked: 2022-11-01 11:00:00 +0000

Seen: 16 times

Last updated: Aug 06 '22