NEW: Master Swift design patterns with my latest book! >>

How to render PDFs using UIGraphicsPDFRenderer

Written by Paul Hudson    @twostraws

UIKit comes with a built-in class for rendering PDFs, and you can render strings, attributed strings, images, and more right to PDF pages. To get started, just create an instance of UIGraphicsPDFRenderer with the paper size you want, then call its pdfData() method and pass in your drawing instructions. You get back a Data object, which you can then write to disk however you want.

Let’s work through some example code so you can try it out. First, pick a paper size:

// A4 size
let pageRect = CGRect(x: 0, y: 0, width: 595.2, height: 841.8)

// Use this to get US Letter size instead
// let pageRect = CGRect(x: 0, y: 0, width: 612, height: 792)

Next, use that size to create a UIGraphicsPDFRenderer:

let renderer = UIGraphicsPDFRenderer(bounds: pageRect)

Third, decide what you want to render. I’m going to render some attributed text as if we were printing an essay:

let title = "School report\n"
let text = String(repeating: "This is an important report about the weather. ", count: 20)

let titleAttributes = [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 36)]
let textAttributes = [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 12)]

let formattedTitle = NSMutableAttributedString(string: title, attributes: titleAttributes)
let formattedText = NSAttributedString(string: text, attributes: textAttributes)
formattedTitle.append(formattedText)

Once you have your content ready, call pdfData() on your renderer, begin a new page, then render as much as you want:

let data = renderer.pdfData { ctx in
    ctx.beginPage()

    formattedTitle.draw(in: pageRect.insetBy(dx: 50, dy: 50))
}

As you can see, I’ve inset my formatted text by 50 points on all side, which should be enough to allow printers to print it accurately.

Finally, save data somewhere as your finished PDF file.

Available from iOS 10.0

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Get six books for only $150

The Swift Power Pack includes my first six books for one low price, helping you jumpstart a new career in iOS development – check it out!

Click here to visit the Hacking with Swift store >>