-
-
Save nyg/b8cd742250826cb1471f to your computer and use it in GitHub Desktop.
// Thanks to http://www.labs.saachitech.com/2012/10/23/pdf-generation-using-uiprintpagerenderer | |
// Note: including images in the HTML won't work, see here: | |
// https://github.com/nyg/HTMLWithImagesToPDF | |
import UIKit | |
// 1. Create a print formatter | |
let html = "<b>Hello <i>World!</i></b>" | |
let fmt = UIMarkupTextPrintFormatter(markupText: html) | |
// 2. Assign print formatter to UIPrintPageRenderer | |
let render = UIPrintPageRenderer() | |
render.addPrintFormatter(fmt, startingAtPageAt: 0) | |
// 3. Assign paperRect and printableRect | |
let page = CGRect(x: 0, y: 0, width: 595.2, height: 841.8) // A4, 72 dpi | |
render.setValue(page, forKey: "paperRect") | |
render.setValue(page, forKey: "printableRect") | |
// 4. Create PDF context and draw | |
let pdfData = NSMutableData() | |
UIGraphicsBeginPDFContextToData(pdfData, .zero, nil) | |
for i in 0..<render.numberOfPages { | |
UIGraphicsBeginPDFPage(); | |
render.drawPage(at: i, in: UIGraphicsGetPDFContextBounds()) | |
} | |
UIGraphicsEndPDFContext(); | |
// 5. Save PDF file | |
guard let outputURL = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("output").appendingPathExtension("pdf") | |
else { fatalError("Destination URL not created") } | |
pdfData.write(to: outputURL, atomically: true) | |
print("open \(outputURL.path)") // command to open the generated file |
I also faced with image issue, just wonder if this resolved I've tried a few solutions but it still does not work for me. I tried to save image to the files and used base 64 image, but still with no luck
https://stackoverflow.com/questions/66251424/creating-pdf-file-with-uiimage-inserted-to-html-code
Hey,
I think you need to use javascript with your HTML code to load image in web view and then create a pdf
Use evaluateJavaScript() to run javascript in web view
Hey,
I think you need to use javascript with your HTML code to load image in web view and then create a pdf
Use evaluateJavaScript() to run javascript in web view
Now all works good! I used link above https://github.com/nyg/HTMLWithImagesToPDF in a wrong way. Image is in the PDF file now. thanks
It should be UIGraphicsBeginPDFContextToData(pdfData, page, nil)
instead of UIGraphicsBeginPDFContextToData(pdfData, .zero, nil)
to have the correct PDF page size and prevent content from being cut off.
Objective-C Version