Skip to content

Instantly share code, notes, and snippets.

@nyg
Last active May 9, 2025 20:44
Show Gist options
  • Save nyg/b8cd742250826cb1471f to your computer and use it in GitHub Desktop.
Save nyg/b8cd742250826cb1471f to your computer and use it in GitHub Desktop.
iOS, Swift: Create a PDF file from an HTML string.
// 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
@matrosovDev
Copy link

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

@startover205
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment