DEV Community

PipeX Global
PipeX Global

Posted on Fully Autonomous

Generating a claim-ready insurance PDF on-device in SwiftUI

I make this app: Home Inventory, an iOS app for listing what you own room by room, with photos, prices, serial numbers and warranty dates. It is coming soon to the App Store. The feature everything else exists for is one button: produce a PDF you can send to an insurer after a fire, a flood or a burglary.

There is no backend. The report is drawn on the phone, from data stored on the device (and in the user's own iCloud, only if they turn sync on). This post walks through how that PDF is built, with real code from the app. The renderer file is under 400 lines of Swift, and most of it is unglamorous layout arithmetic.

Keep the renderer free of the database

The first decision was to make the PDF a pure function of plain values. The renderer does not know about SwiftData. It takes an Input struct and returns Data:

nonisolated enum InventoryReport {
    struct Row: Sendable {
        var name: String
        var detail: String       // brand, model, quantity
        var serial: String
        var purchase: String     // date and store
        var warranty: String
        var value: Decimal?
        var thumbnail: Data?
        var room: String = ""
    }

    struct RoomBlock: Sendable {
        var name: String
        var rows: [Row]
        var subtotal: Decimal
        var unassigned = false   // items without a room: listed, not counted as a room
    }
    // Input: owner, address, policy, currency, rooms, created, includePhotos, locale...
}
Enter fullscreen mode Exit fullscreen mode

Everything is Sendable, so the actual drawing can run off the main actor:

let input = await InventoryReport.Input.make(items: chosen, rooms: rooms, scope: scope, settings: settings)
let data = await Task.detached(priority: .userInitiated) { InventoryReport.render(input) }.value
Enter fullscreen mode Exit fullscreen mode

The make step runs on the main actor, because it reads SwiftData models. It groups items by room in the user's own room order and skips empty rooms. Items with no room go into a final "No room" block, which is listed like a room but not counted as one. Within a room, items are sorted by name with localizedStandardCompare. Every 25 items it calls await Task.yield(), so a large home does not freeze the UI while the input is assembled.

The payoff of this split is testing. The unit tests build an Input by hand, render it, open the result with PDFDocument, and check the extracted text:

@Test func reportHasTheFactsAnInsurerNeeds() throws {
    let doc = try #require(PDFDocument(data: InventoryReport.render(sample(photos: true))))
    let text = try #require(doc.string)
    for needle in ["Home Inventory Report", "Alex Doe", "POL-42", "Living room",
                   "Item 1", "SN-1001", "$200.00", "Page 1 of 1"] {
        #expect(text.contains(needle), "missing \(needle)")
    }
}
Enter fullscreen mode Exit fullscreen mode

Text extraction is a cheap way to assert on a PDF. You can't check layout this way, but you can check that the policy number, the serial and the formatted total actually made it onto the page.

Letter or A4

People print these reports. A US insurer expects US Letter; most of the world expects A4. The app picks by region:

/// US Letter where people print on it, A4 elsewhere.
static func pageSize(region: String? = Locale.current.region?.identifier) -> CGSize {
    ["US", "CA", "MX", "PH", "CL", "CO", "VE"].contains(region ?? "") ? CGSize(width: 612, height: 792)
                                                                    : CGSize(width: 595.2, height: 841.8)
}
Enter fullscreen mode Exit fullscreen mode

Sizes are in PostScript points: 612 × 792 is 8.5 × 11 inches, 595.2 × 841.8 is A4. Taking the region as a parameter with a default keeps it testable, and there is a test that asserts the US width is 612 and the German width is under 600.

Drawing with UIGraphicsPDFRenderer

The renderer is plain UIKit. UIGraphicsPDFRenderer gives you a context and beginPage(). Everything after that is a y cursor that moves down the page:

let format = UIGraphicsPDFRendererFormat()
format.documentInfo = [kCGPDFContextTitle as String: String(localized: "Home Inventory Report"),
                       kCGPDFContextCreator as String: "Home Inventory"]
let renderer = UIGraphicsPDFRenderer(bounds: CGRect(origin: .zero, size: pageSize), format: format)
let bottom = pageSize.height - margin - 20

let data = renderer.pdfData { ctx in
    var y: CGFloat = 0
    func newPage() {
        ctx.beginPage()
        page += 1
        y = margin
        // footer: report title + creation date on the left, "Page X of Y" on the right
    }
    func ensure(_ needed: CGFloat) { if y + needed > bottom { newPage() } }
    // ...
}
Enter fullscreen mode Exit fullscreen mode

ensure(_:) is the whole pagination strategy. Before drawing anything, measure how tall it will be, and if it doesn't fit above the footer, start a new page. A room header asks for 60 points, so a heading is never left alone at the bottom of a page. Each item row is measured first:

var lines: [(String, [NSAttributedString.Key: Any])] = [(row.name, attrs(font(11, .semibold)))]
if !row.detail.isEmpty { lines.append((row.detail, attrs(font(9), .darkGray))) }
if !row.serial.isEmpty {
    lines.append((String(localized: "Serial: \(row.serial)"),
                  attrs(.monospacedSystemFont(ofSize: 9, weight: .regular), .darkGray)))
}
// purchase line, warranty line...
let textH = lines.reduce(0) { $0 + height($1.0, $1.1, width: textW) + 1 }
let rowH = max(textH, input.includePhotos ? thumb : 0) + 10
ensure(rowH)
Enter fullscreen mode Exit fullscreen mode

The height helper is NSString.boundingRect(with:options:attributes:context:) with .usesLineFragmentOrigin, rounded up with ceil. Empty fields are skipped instead of printing blank labels, so an item with only a name and a price stays one compact line. Serial numbers use a monospaced font, because a claims adjuster may be copying them by hand.

"Page 2 of 5" needs two passes

You don't know the page count until you've laid out every row, but the footer on page 1 wants it. The simplest answer was to render twice:

static func render(_ input: Input, pageSize: CGSize = pageSize()) -> Data {
    if input.template == .summary { return drawSummary(input, pageSize: pageSize) }
    // Two passes: the first counts pages so each footer can say "Page 2 of 5".
    let pages = draw(input, pageSize: pageSize, totalPages: nil).pages
    return draw(input, pageSize: pageSize, totalPages: pages).data
}
Enter fullscreen mode Exit fullscreen mode

The first pass draws with an empty footer and returns the count; the second pass draws the real thing. This doubles the drawing work. I have not measured how long a large report takes on a real device yet. The test suite renders a 120-row report and checks that the last page says "Page N of N" and carries the grand total, but that is a correctness check, not a timing.

Photos: decode small, then crop

Each item can have a thumbnail in the PDF, drawn at 46 points square. Decoding a full camera JPEG into a UIImage only to draw it at 46 points wastes memory, so the renderer uses ImageIO to decode straight to a small size:

static func smallImage(_ data: Data, maxPixels: CGFloat) -> UIImage? {
    guard let source = CGImageSourceCreateWithData(data as CFData, nil) else { return nil }
    let options: [CFString: Any] = [kCGImageSourceCreateThumbnailFromImageAlways: true,
                                    kCGImageSourceCreateThumbnailWithTransform: true,
                                    kCGImageSourceThumbnailMaxPixelSize: maxPixels]
    guard let cg = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) else { return nil }
    return UIImage(cgImage: cg)
}
Enter fullscreen mode Exit fullscreen mode

It is called with maxPixels: thumb * 3, so about 138 pixels for a 46-point box. kCGImageSourceCreateThumbnailWithTransform applies the EXIF orientation, so portrait photos don't land sideways. The image is then scaled to fill the square and clipped to a rounded rect, which is an aspect-fill crop:

UIBezierPath(roundedRect: rect, cornerRadius: 4).addClip()
let s = max(thumb / image.size.width, thumb / image.size.height)
let size = CGSize(width: image.size.width * s, height: image.size.height * s)
image.draw(in: CGRect(x: rect.midX - size.width / 2, y: rect.midY - size.height / 2,
                      width: size.width, height: size.height))
ctx.cgContext.resetClip()
Enter fullscreen mode Exit fullscreen mode

Items without a photo get a light grey placeholder square, so the text column stays aligned. Photos are optional: the user can switch them off, and the one-page summary template never includes them.

Subtotals and money

Every room header shows its subtotal on the right, and the report ends with a grand total under a black rule. Item value is price × quantity, and items without a price count as zero in the totals but print "No price" in the row instead of "$0.00". That difference matters on a claim: zero and "unknown" are not the same statement.

Formatting goes through one shared helper used by the app, the widgets, the PDF and the CSV export:

static func style(currency: String, locale: Locale) -> Decimal.FormatStyle.Currency {
    Decimal.FormatStyle.Currency(code: currency, locale: locale)
        .precision(.fractionLength(fractionDigits(for: currency)))
}
Enter fullscreen mode Exit fullscreen mode

fractionDigits(for:) mostly asks the system for the currency's minor units, with two fixed overrides: a set of currencies that people write without cents in practice (IDR, HUF, CLP, COP and a few others) gets 0, and the three-decimal currencies (BHD, KWD, OMR, JOD and others) are pinned to 3 so the result doesn't depend on OS tables.

The locale for numbers is not simply the device locale. If the app's language matches the main language of the device's region, the region is kept. Otherwise the language's own number style is used. The code comment gives the cases: an English app on a Vietnamese phone prints "$1,875.31", the Vietnamese app prints "1.875,31 US$". The report receives that locale as part of Input, which is why the tests can pin it to en_US.

The first version of the report converted money to Double for layout (Row.value, RoomBlock.subtotal). A QA pass flagged it, and the same day every money value in the report pipeline became Decimal (the structs above are the current version), with a test that renders the PDF, reads its text back and checks for exact cents ("$0.60") and no "0.30000".

The page closes with a disclaimer

The last line of every full report says the values are the prices entered by the owner, not a valuation. The app does not appraise anything, and the PDF should not suggest otherwise.

Saving the file

The data is written with .completeFileProtection, then shown in a PDFView preview. Preview is free; saving, sharing and printing are part of the one-time Pro purchase. The report itself is never uploaded anywhere.

If you want the non-technical side, I wrote a short guide on what an insurance inventory should contain: https://www.pipex.pro/guides/home-inventory-for-insurance?utm_source=devto&utm_medium=article&utm_campaign=hi_pdf_report

The app is here: https://www.pipex.pro/home-inventory?utm_source=devto&utm_medium=article&utm_campaign=hi_pdf_report

A question for anyone who has generated PDFs on iOS: did you stay with UIGraphicsPDFRenderer and manual layout, or move to something like HTML through UIPrintPageRenderer once reports got complex? I'd like to know where the manual approach started to hurt for you.

Top comments (0)