Skip to content

Instantly share code, notes, and snippets.

@jplazcano87
Forked from nyg/iOSCreatePDF.swift
Created December 14, 2015 15:16
Show Gist options
  • Save jplazcano87/192aac52acefd667d75a to your computer and use it in GitHub Desktop.
Save jplazcano87/192aac52acefd667d75a 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
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, startingAtPageAtIndex: 0)
// 3. Assign paperRect and printableRect
let page = CGRect(x: 0, y: 0, width: 595.2, height: 841.8) // A4, 72 dpi
let printable = CGRectInset(page, 0, 0)
render.setValue(NSValue(CGRect: page), forKey: "paperRect")
render.setValue(NSValue(CGRect: printable), forKey: "printableRect")
// 4. Create PDF context and draw
let pdfData = NSMutableData()
UIGraphicsBeginPDFContextToData(pdfData, CGRectZero, nil)
for i in 1...render.numberOfPages() {
UIGraphicsBeginPDFPage();
let bounds = UIGraphicsGetPDFContextBounds()
render.drawPageAtIndex(i - 1, inRect: bounds)
}
UIGraphicsEndPDFContext();
// 5. Save PDF file
let path = "\(NSTemporaryDirectory())file.pdf"
pdfData.writeToFile(path, atomically: true)
print("open \(path)") // command to open the generated file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment