NEW: Got a question? Get help on our new forums! >>

How to render an NSAttributedString to a PDF

Swift version: 5.1

Paul Hudson    @twostraws   

Attributed strings contain all the formatting they need to go straight to images, PDFs, and other visual output, although it does take a little setup to get a good PDF out.

First, create your attributed string:

let attributedString = NSAttributedString(string: "This is a test", attributes: [NSAttributedString.Key.foregroundColor: UIColor.red])

Next, wrap that inside a UISimpleTextPrintFormatter, which is responsible for layout out that string over as many pages as needed:

let printFormatter = UISimpleTextPrintFormatter(attributedText: attributedString)

You can then put that formatter inside a page renderer, telling it to start printing at page 0:

let renderer = UIPrintPageRenderer()
renderer.addPrintFormatter(printFormatter, startingAtPageAt: 0)

Next you need to define a few sizes: how big your paper size is, along with what margins you want.

// A4 size
let pageSize = CGSize(width: 595.2, height: 841.8)

// Use this to get US Letter size instead
// let pageSize = CGSize(width: 612, height: 792)

// create some sensible margins
let pageMargins = UIEdgeInsets(top: 72, left: 72, bottom: 72, right: 72)

// calculate the printable rect from the above two
let printableRect = CGRect(x: pageMargins.left, y: pageMargins.top, width: pageSize.width - pageMargins.left - pageMargins.right, height: pageSize.height - pageMargins.top - pageMargins.bottom)

// and here's the overall paper rectangle
let paperRect = CGRect(x: 0, y: 0, width: pageSize.width, height: pageSize.height)

You can now pass the paper and printable rectangles to the page renderer, like this:

renderer.setValue(NSValue(cgRect: paperRect), forKey: "paperRect")
renderer.setValue(NSValue(cgRect: printableRect), forKey: "printableRect")

The next step is to create an empty instance of NSMutableData, then ask UIKit to render into that data object:

let pdfData = NSMutableData()

UIGraphicsBeginPDFContextToData(pdfData, paperRect, nil)
renderer.prepare(forDrawingPages: NSMakeRange(0, renderer.numberOfPages))

Now all that remains is to render draw each page into the bounds of the PDF context, like this:

let bounds = UIGraphicsGetPDFContextBounds()

for i in 0  ..< renderer.numberOfPages {
    UIGraphicsBeginPDFPage()

    renderer.drawPage(at: i, in: bounds)
}

UIGraphicsEndPDFContext()

At this point your pdfData value contains the finished PDF, so you can write it wherever you want:

do {
    try pdfData.write(to: yourURL)
} catch {
    print(error.localizedDescription)
}
Hacking with Swift is sponsored by Instabug

SPONSORED Catch bugs as soon as they happen and know exactly why a crash occurred by integrating Instabug's SDK in one minute. You will automatically receive device data, network logs, and reproduction steps with every bug and crash report.

Learn more and get started for free

Sponsor Hacking with Swift and reach the world's largest Swift community!

Cascable unleashes the power of your camera and unlocks powerful workflows for shooting, managing, and geotagging your photos.

Available from iOS 4.2

Similar solutions…

About the Swift Knowledge Base

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

BUY OUR BOOKS
Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.6/5