NEW! Pre-order my latest book, Testing Swift! >>

How to render PDFs using UIGraphicsPDFRenderer

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 = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 36)]
let textAttributes = [NSAttributedString.Key.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.

Download for free!

Want a free 75-minute video teaching functional programming, protocol-oriented programming, and more? This is your lucky day!

MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Click here to visit the Hacking with Swift store >>