Creating PDF file with UIImage inserted to HTML code

480 Views Asked by At

This is a good documented example how to create a pdf file using html string.

All works good excluding image

I have UIImage object which I would like to use in HTML code when I preview it via WKWebView

<img src="#LOGO_IMAGE#" style="width:100%; max-width:300px; background-color: #cdcdcd">

This is how I load WKWebView

webView.loadHTMLString(htmlStr, baseURL: nil)

I found a solution how to do it here using Base64 encoding. And previewing HTML content in WKWebView looks good. Image is on the web page.

But when I generate a PDF file using html string which contains my Base64 encoded image in src tag the generated PDF file won't show up image.

So the first image is a preview in WKWebView:

enter image description here

and the second is generate PDF based on the same html content:

enter image description here

As you may see that the logo is missing.

I will skip entire HTML code creation function, but here is a code how I create PDF from it:

func exportHTMLContentToPDF(HTMLContent: String) {
        let printPageRenderer = CustomPrintPageRenderer()
        let printFormatter = UIMarkupTextPrintFormatter(markupText: HTMLContent)
        printPageRenderer.addPrintFormatter(printFormatter, startingAtPageAt: 0)
        let pdfData = drawPDFUsingPrintPageRenderer(printPageRenderer: printPageRenderer)
        pdfFilename = getDocDir() + "/Invoice" + invoiceNumber + ".pdf"
        pdfData?.write(toFile: pdfFilename, atomically: true)

        print(pdfFilename)
    }
    
    func drawPDFUsingPrintPageRenderer(printPageRenderer: UIPrintPageRenderer) -> NSData! {
        let data = NSMutableData()
     
        UIGraphicsBeginPDFContextToData(data, CGRect.zero, nil)
        UIGraphicsBeginPDFPage()
        printPageRenderer.drawPage(at: 0, in: UIGraphicsGetPDFContextBounds())
        UIGraphicsEndPDFContext()
     
        return data
    }
    
    func getDocDir() -> String {
        return NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
    }
1

There are 1 best solutions below

0
On

This is a link to a working code https://github.com/nyg/HTMLWithImagesToPDF

There are a lot of variants how to load image to PDF from html file.

I used base46 and it works for me. But there are different solutions which are specified in the code.

Very useful