skip to content

With UIGraphicsPDFRenderer, how do you export a multi-page PDF of a driver's day of deliveries, and where do page breaks come from?

level: seniorimportance: nice to knowfreq 28%

answer

  1. page size in points, 72 per inch
  2. nothing draws before the first page
  3. file output or in-memory data
  4. the renderer never paginates for you
  5. links use the flipped PDF space

basics

~20 s

Create a UIGraphicsPDFRenderer with the page bounds, call writePDF(to:withActions:) or pdfData(actions:), and call beginPage() before drawing each page. The renderer never paginates: your code measures each row and starts a new page when it would overflow.

solid answer

~40 s

I create `UIGraphicsPDFRenderer(bounds:format:)` with a page rect in points, 612 × 792 for US Letter, and put a title in the format's `documentInfo` under `kCGPDFContextTitle`. `writePDF(to:withActions:)` streams to a file and throws on failure in Swift; `pdfData(actions:)` returns `Data` in memory, which suits small documents. Inside the closure I must call `beginPage()` before any drawing. Page breaks are mine: I keep a running y, and when the next delivery row would cross the bottom margin I call `beginPage()` again and reset y. Drawing uses UIKit's top-left coordinates, so `NSString.draw(at:withAttributes:)` and `UIImage.draw(in:)` work as in a view. Paths and text stay vector; a signature image keeps its own pixels, so I downscale large ones first. The renderer is iOS 10; the older `UIGraphicsBeginPDFContextToData` functions still exist and are not deprecated.

code

swift · 27 lines
swift
import UIKit

struct Delivery { let address: String; let signature: UIImage }

func writeDayReport(_ deliveries: [Delivery], to url: URL) throws {
    let page = CGRect(x: 0, y: 0, width: 612, height: 792)   // US Letter, in points
    let format = UIGraphicsPDFRendererFormat()
    format.documentInfo = [kCGPDFContextTitle as String: "Deliveries"]
    let renderer = UIGraphicsPDFRenderer(bounds: page, format: format)
    let rowHeight: CGFloat = 120
    let margin: CGFloat = 36

    try renderer.writePDF(to: url) { context in
        var y = CGFloat.infinity                    // forces a page before the first row
        for delivery in deliveries {
            if y + rowHeight > page.maxY - margin {
                context.beginPage()                 // nothing may be drawn before this
                y = margin
            }
            (delivery.address as NSString).draw(
                at: CGPoint(x: margin, y: y),
                withAttributes: [.font: UIFont.preferredFont(forTextStyle: .body)])
            delivery.signature.draw(in: CGRect(x: margin, y: y + 28, width: 200, height: 80))
            y += rowHeight
        }
    }
}

go deeper

for a junior

Recall the two output methods, writePDF(to:withActions:) and pdfData(actions:), and that each page starts with beginPage().

for a middle

Explain page bounds in points, documentInfo metadata, and that the drawing context uses UIKit's top-left coordinates.

for a senior

Own pagination yourself with measured rows, keep file size down by downscaling images, and choose file output and a background task for long reports.

for a principal

Decide whether on-device PDF generation is worth owning versus a simpler format, weighing layout code, fonts and file size against offline needs.

## The job At the end of a shift, a delivery-driver app exports one PDF listing the day's deliveries: an address, a time and the customer's signature for each, as many pages as it takes. UIKit's tool is **`UIGraphicsPDFRenderer`**, available since iOS 10, which draws with the same Core Graphics and UIKit calls as a view but records vector PDF pages. ## Setting up the renderer - **Bounds.** `UIGraphicsPDFRenderer(bounds:format:)` takes the default page rectangle in **points**, where a point is 1/72 inch. US Letter is 8.5 × 11 inches, so 612 × 792; A4 is about 595 × 842. - **Format.** `UIGraphicsPDFRendererFormat` has one property of its own, `documentInfo`, a dictionary of document metadata keyed by Core Graphics' PDF context keys such as `kCGPDFContextTitle`, `kCGPDFContextAuthor` and `kCGPDFContextCreator`. - **Output.** Two methods run the drawing closure: - `writePDF(to:withActions:)` writes to a file URL. Its Objective-C form returns `BOOL` with an error pointer, so in Swift it **throws**. - `pdfData(actions:)` returns the whole document as `Data` in memory. Apple's documentation says one renderer can produce several PDFs with the same configuration. ## Pages are explicit Apple's documentation is direct: before issuing drawing instructions, you **must create a page** with `beginPage()` or `beginPage(withBounds:pageInfo:)` on the `UIGraphicsPDFRendererContext` passed to the closure. Each further `beginPage()` call adds a page. `beginPage(withBounds:pageInfo:)` overrides the size for one page, for example a landscape summary page. `pdfContextBounds` reports the current bounds. The renderer does **not** paginate. Drawing below the page's bottom edge falls outside the page and is not shown; nothing flows onto a new page. So the export loop owns the layout: 1. Start with a y position that forces a page before the first row. 2. For each delivery, check whether the row's height fits above the bottom margin. 3. If not, call `beginPage()` and reset y to the top margin. 4. Draw the row at y and advance y by the row's height. For rows of varying height, measure first, for example with `NSAttributedString`'s bounding-rect methods, then decide. Apple's documentation suggests TextKit or Core Text when a PDF carries a lot of text, because those handle text layout across areas. ## Drawing on a page The renderer makes its context current with UIKit's orientation: origin at the top-left, y increasing downward. That means: - `NSString.draw(at:withAttributes:)` and `NSAttributedString.draw(in:)` place text as in a view; - `UIImage.draw(in:)` places a signature image upright; - `UIBezierPath` strokes and `CGContext` calls through `context.cgContext` work as in `draw(_:)`. Paths and text are recorded as **vector** content, so they stay sharp at any zoom. An image is embedded as image data, and drawing a large bitmap small does not shrink what it carries into the file; a signature captured at full screen resolution should be rendered down to its printed size first. ## Links and destinations `UIGraphicsPDFRendererContext` can add a URL link with `setURL(_:for:)`, a named destination with `addDestination(withName:at:)`, and a link to it with `setDestinationWithName(_:for:)`. Apple's documentation warns that the two destination methods use the **underlying PDF coordinate space**, whose y-axis is flipped with respect to the coordinate system Core Graphics uses, and suggests converting with the context's `userSpaceToDeviceSpaceTransform`. ## Memory, threads and the older API | Choice | Use when | |---|---| | `writePDF(to:withActions:)` | Long reports, sharing a file, keeping memory flat | | `pdfData(actions:)` | Short documents sent straight to an upload or share sheet | In Swift, the renderer is not isolated to the main actor, so a long export can run in a background task with its inputs captured first, keeping the UI responsive. Before iOS 10, PDF output used `UIGraphicsBeginPDFContextToFile` or `UIGraphicsBeginPDFContextToData`, `UIGraphicsBeginPDFPage()` per page and `UIGraphicsEndPDFContext()`. Unlike the image-context functions, these carry no deprecation marking in the iOS 27.1 SDK; the renderer is preferred for its block scope, which cannot leave a context open. Common mistakes: - Drawing before the first `beginPage()`. - Expecting long content to flow onto new pages by itself. - Embedding full-resolution photos in a document meant for email. - Building a 200-page report with `pdfData(actions:)` on the main thread.

  • How would you add a page-number footer to every page of the delivery report?
    Wrap `beginPage()` in a small helper that calls it, increments a page counter and immediately draws the footer text at the bottom of `pdfContextBounds`. Because the renderer never paginates by itself, every page break goes through that helper, so no page misses its footer.
  • A finance reviewer wants the report to open on a summary page in landscape; what changes?
    Start the document with `beginPage(withBounds:pageInfo:)` passing a 792 × 612 rect for that one page, draw the summary, then call `beginPage()` for the delivery pages, which use the renderer's default portrait bounds again.

  • Expects UIGraphicsPDFRenderer to start a new page when drawing passes the bottom edge.
  • Draws content before calling beginPage() in the drawing closure.
  • Gives the page bounds in pixels at screen scale instead of points.
  • Says UIGraphicsBeginPDFContextToData is deprecated in the current SDK.
  • Thinks drawing a large photo small in a PDF shrinks the embedded image.

Assumes the iOS 27.1 SDK: UIGraphicsPDFRenderer is iOS 10, and the older UIGraphicsBeginPDFContextToData functions carry no deprecation marking.