2

I want to use a WKWebView to render a document. I made Invoice.html and Invoice.css and put them into bundle. When I load Invoice.html to Safari (by dragging file) everything looks OK. But not in WKWebView. I tried:

Simple way:

let htmlUrl = URL(fileReferenceLiteralResourceName: "Invoice.html")
let html = String.init(contentsOf: htmlUrl)
webView.loadHTMLString(html, baseURL: nil)

Beginning of Invoice.html looks like this:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta charset="utf-8" />
        <title>Invoice</title>
        <link REL=StyleSheet HREF="./Invoice.css" TYPE="text/css" MEDIA=screen>
            </head>
    <body id="Invoice" xml:lang="en-US">
        <div class="page">
            <div>
                <p>FAKTURA VAT</p>
            </div>
            <div>
                <div>
                    <p>SPRZEDAWCA SELLER: </p>
                </div>
                <p></p>

I could see text in WKWebView but not styled.

WKWebView Extension

extension WKWebView {
    func injectCSSFrom(url: URL) {


        let css = try! String(contentsOf: url).split(separator: "\n")
        //let css = "body { background-color : #aabbcc };"
        print (css)
        let js = "var style = document.createElement('style'); style.innerHTML = '\(css)'; document.head.appendChild(style);"

        evaluateJavaScript(js) {(result, error) in
            if let error = error {
                print("DOES NOT WORK", error)
            }
        }
    }
}

prints :

body {
    margin: 0;
    padding: 0;
    background-color: #FA0000;
    font: 7pt "Helvetica";
}

.page {
    width: 21cm;
    height: 29.7cm;
    padding: 1.5cm;
    border: 1px #D3D3D3 solid;
    border-radius: 0px;
    background: white;
}

Same like by simple way. Nothing, no style, no background color. But if I change let css = "body { background-color : #aabbcc };" at least background color changes.

In both cases evaluate... throws an error Error Domain=WKErrorDomain Code=4 "A JavaScript exception occurred" UserInfo={WKJavaScriptExceptionLineNumber=1, WKJavaScriptExceptionMessage=SyntaxError: Unexpected EOF, WKJavaScriptExceptionColumnNumber=0, WKJavaScriptExceptionSourceURL=about:blank, NSLocalizedDescription=A JavaScript exception occurred}

Is a simple and versatile way to attach css to html generated locally?

Łukasz
  • 773
  • 5
  • 23

0 Answers0