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:
and the second is generate PDF based on the same html content:
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]
}