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.
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
Asked: 2022-11-01 11:00:00 +0000
Seen: 8 times
Last updated: Aug 06 '22
What steps can I take to prevent my webpage from slowing down when all parts of a div are displayed?
What is the method to include a loading spinner when a button is clicked?
How can Recursive Quote Embedding for HTML and Javascript be made more advanced?
Is it feasible to utilize a Toggle Button to switch among multiple classes exceeding 2?
What is the process for generating a dynamic subdomain/URL using vue.js?
How can I create a transition on click using CSS without the need for JavaScript?