Last active
May 9, 2025 20:44
-
-
Save nyg/b8cd742250826cb1471f to your computer and use it in GitHub Desktop.
iOS, Swift: Create a PDF file from an HTML string.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 |
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
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