Generate PDFs Programmatically on iOS

PSPDFKit for iOS offers several different ways to programmatically create PDF files. Check out the following guides for generating a:

Optionally, you can also use Apple’s built-in APIs provided by UIKit to generate a PDF.

Using UIKit

For maximum flexibility, you can write your own UIKit or Core Graphics drawing code to generate PDFs. You need to take care to correctly handle line and page breaks. This is easiest with the UIGraphicsPDFRenderer class introduced in iOS 10. The documentation is detailed and has easy-to-understand examples.

Here’s an example of using UIGraphicsPDFRenderer:

import UIKit

let outputFileURL: URL = ...

let pdfRenderer = UIGraphicsPDFRenderer(bounds: CGRect(x: 0, y: 0, width: 595, height: 842))

do {
    try pdfRenderer.writePDF(to: outputFileURL) { context in

        let attributes: [NSAttributedString.Key: Any] = [
            .font : UIFont.systemFont(ofSize: 36, weight: .semibold)

        let text = "This PDF was made using\na tutorial from PSPDFKit."

        (text as NSString).draw(at: CGPoint(x: 20, y: 20), withAttributes: attributes)
} catch {
    print("Could not create PDF file: \(error)")

If you already have a view that draws into a graphics context using Core Graphics or UIKit drawing calls, you can reuse that drawing code.