Mulgard Mulgard - 1 year ago 132
HTML Question

UIMarkupTextPrintFormatter never renders base64 images

Im creating a pdf file out of html content in swift 3.0:

func exportHtmlContentToPDF(HTMLContent: String, filePath: String) {
// let webView = UIWebView(frame: CGRect(x: 0, y: 0, width: 694, height: 603));

// webView.loadHTMLString(HTMLContent, baseURL: nil);

let pdfPrinter = PDFPrinter();
let printFormatter = UIMarkupTextPrintFormatter(markupText: HTMLContent);
// let printFormatter = webView.viewPrintFormatter();

pdfPrinter.addPrintFormatter(printFormatter, startingAtPageAt: 0);

let pdfData = self.drawPDFUsingPrintPageRenderer(printPageRenderer: pdfPrinter);

pdfData?.write(toFile: filePath, atomically: true);

func drawPDFUsingPrintPageRenderer(printPageRenderer: UIPrintPageRenderer) -> NSData! {
let data = NSMutableData();

UIGraphicsBeginPDFContextToData(data,, nil);

printPageRenderer.prepare(forDrawingPages: NSMakeRange(0, printPageRenderer.numberOfPages));

let bounds = UIGraphicsGetPDFContextBounds();

for i in 0...(printPageRenderer.numberOfPages - 1) {

printPageRenderer.drawPage(at: i, in: bounds);


return data;

Everything is rendered fine except my base64 encoded images. The HTML content itself in a webview or inside safari or chrome browser is presented correctly and is showing all images correctly. But the images are never rendered into the pdf.

Why are the images not rendered and how can I get them to be rendered?

mz2 mz2
Answer Source

This happens because WebKit first parses the HTML into a DOM, and renders content on multiple event loop cycles. You therefore need to wait for not just the page DOM to be ready but for the resource loading to be complete. As you also suggest, you need to refactor your code such that the webview gets loaded first, and you only then export its contents.

To determine the correct time to fire the export, you can observe for the state of the DOM document in the web view. There are multiple ways to do this, but the most readable option I find is a port of an answer to a related Objective-C question: in your UIWebViewDelegate implementation, implement webViewDidFinishLoad in the following way to monitor document.readyState:

    func webViewDidFinishLoad(_ webView: UIWebView) {

        guard let readyState = webView.stringByEvaluatingJavaScript(from: "document.readyState"),
            readyState == "complete" else
            // document not yet parsed, or resources not yet loaded.

        // This is the last webViewDidFinishLoad call --> export.
        // There is a problem with this method if you have JS code loading more content:
        // in that case -webViewDidFinishLoad can get called again still after document.readyState has already been in state 'complete' once or more.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download