Unwanted right margin when generating a PDF from a WKWebView

Viewed 239

I'm trying to save the current WKWebView view as a PDF. This is the HTML that is loaded into the webview:

<!DOCTYPE html>
<html lang="en" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title>PDF neve</title>
        <style type="text/css">
            * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }

            body {
                border: 1px solid red;
            }

            div {
                height: 400px;
            }

        </style>
    </head>
    <body>
        <div>lorem</div>
    </body>
</html>

Which is rendered correctly, the body's border goes from side to side:

enter image description here

However when i generate a PDF from this WebView with the following code:

class func generate() -> Data {

    // assign the print formatter to the print page renderer
    let renderer = UIPrintPageRenderer()
    let printFormatter = wkWebView.viewPrintFormatter()
    renderer.addPrintFormatter(printFormatter, startingAtPageAt: 0)

    // assign paperRect and printableRect values
    let page = CGRect(x: 0, y: 0, width: 595.2, height: 841.8) // A4, 72 dpi
    renderer.setValue(page, forKey: "paperRect")
    renderer.setValue(page, forKey: "printableRect")

    // create pdf context and draw each page
    let pdfData = NSMutableData()
    UIGraphicsBeginPDFContextToData(pdfData, .zero, nil)

    for i in 0..<renderer.numberOfPages {
        UIGraphicsBeginPDFPage()
        renderer.drawPage(at: i, in: UIGraphicsGetPDFContextBounds())
    }

    UIGraphicsEndPDFContext();

    // save data to a pdf file and return
    guard nil != (try? pdfData.write(to: outputURL, options: .atomic))
        else { fatalError("Error writing PDF data to file.") }

    return pdfData as Data
}

I got this as a result:

enter image description here

Notice theres a border/spacing issue on the right. Any ideas what might cause this?

1 Answers

For me it worked when I adjusted the width of the page. So play with the value 595.2. For me, a perfect A4 page printed at 612.2 x 1000.0

let page = CGRect(x: 0, y: 0, width: 612.2, height: 1000.0)
Related