Swift version: 5.10
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.
SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure and A/B test your entire paywall UI without any code changes or app updates.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Available from iOS 10.0
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Link copied to your pasteboard.