Export Long Text To PDF Without Cutting It Off
A report looks fine in a scrolling view. Export it as a PDF, and the last six paragraphs disappear below the page. Making the page taller produces a very long sheet. Shrinking the view makes the text harder to read.
For a text report, give the document its own layout. Keep the type size readable, ask Core Text how much fits on each page, and start the next page at that exact boundary.
We’ll build a small plain-text exporter for notes, summaries and audit reports. It uses Foundation, Core Text and Core Graphics, with no third-party dependency. The same report can be exported whether its screen is open or closed.
Download the complete example and checks.
Give the report a paper size
Majid Jabrayilov’s ImageRenderer walkthrough is a useful starting point for exporting a chart or a finite SwiftUI composition. Apple’s ImageRenderer documentation shows how to draw supported views into a PDF context.
A long report needs another decision: where does each page end? A snapshot renderer has no knowledge that you want continuous text to flow into another sheet.
Pratik Sodha’s accepted Stack Overflow answer shows how to continue a Core Text frame onto the next page. We’ll use that boundary, handle a page that cannot fit another line, and reopen the finished PDF to check what the reader receives.
The example uses a roughly A4-sized page, 595 by 842 points, with 54-point margins and a fixed 12-point font. A PDF point is a document coordinate, not a screen pixel. Changing the phone’s display scale should not change the paper size.
Advance by what fits
Put this complete implementation in TextReportPDF.swift. It is verified with Swift 6.4.2 and an iOS 17 deployment target; the Core Text pagination APIs themselves are much older. The explicit nonisolated declarations require Swift 6.1 or later.
import Foundation
import CoreGraphics
import CoreText
nonisolated enum ReportPDFError: Error, Equatable {
case emptyText
case textTooLong
case tooManyPages
case invalidPageSize
case cannotCreateContext
case noProgress(atUTF16Offset: Int)
}
nonisolated enum TextReportPDF {
static func render(
_ text: String,
pageSize: CGSize = CGSize(width: 595, height: 842)
) throws -> Data {
guard text.utf16.prefix(100_001).count <= 100_000 else {
throw ReportPDFError.textTooLong
}
guard !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
throw ReportPDFError.emptyText
}
let source = NSAttributedString(
string: text,
attributes: [
NSAttributedString.Key(kCTFontAttributeName as String):
CTFontCreateWithName("Helvetica" as CFString, 12, nil),
NSAttributedString.Key(kCTForegroundColorAttributeName as String):
CGColor(gray: 0, alpha: 1)
]
)
let margin: CGFloat = 54
let minimumColumnWidth: CGFloat = 144
guard pageSize.width.isFinite, pageSize.height.isFinite,
pageSize.width >= margin * 2 + minimumColumnWidth, pageSize.height > margin * 2,
pageSize.width <= 2_000, pageSize.height <= 2_000 else {
throw ReportPDFError.invalidPageSize
}
var page = CGRect(origin: .zero, size: pageSize)
let body = page.insetBy(dx: margin, dy: margin)
let path = CGPath(rect: body, transform: nil)
let framesetter = CTFramesetterCreateWithAttributedString(source)
let output = NSMutableData()
guard let consumer = CGDataConsumer(data: output),
let context = CGContext(consumer: consumer, mediaBox: &page, nil) else {
throw ReportPDFError.cannotCreateContext
}
do {
var offset = 0
var pageCount = 0
while offset < source.length {
try Task.checkCancellation()
guard pageCount < 250 else { throw ReportPDFError.tooManyPages }
let frame = CTFramesetterCreateFrame(
framesetter, CFRange(location: offset, length: 0), path, nil
)
let visible = CTFrameGetVisibleStringRange(frame)
guard visible.location == offset, visible.length > 0,
visible.length <= source.length - offset else {
throw ReportPDFError.noProgress(atUTF16Offset: offset)
}
context.beginPDFPage(nil)
context.textMatrix = .identity
CTFrameDraw(frame, context)
context.endPDFPage()
offset += visible.length
pageCount += 1
}
} catch {
context.closePDF()
throw error
}
context.closePDF()
return output as Data
}
}
CFRange(location: offset, length: 0) means “start here and use as much remaining text as fits.” Zero is the special framesetter convention, not a request to draw zero characters.
CTFrameGetVisibleStringRange returns what actually fits. Advance by its length. Don’t estimate a character count from the page height, and don’t keep drawing the original range on every page.
These offsets belong to the attributed string’s UTF-16 backing store. source.length matches that coordinate system. Swift’s text.count counts extended grapheme clusters, so it can disagree for emoji and combining characters. Mixing the two can make a loop stop while text remains.
The exporter requires a text column at least two inches (144 points) wide. In a one-point column, Core Text can count a whole glyph as laid out while its ink extends past the margin. A positive fitted range tells us where to resume. It cannot certify every glyph’s painted bounds.
The no-progress guard handles a different case. A rectangle can have positive dimensions and still be too short for one line. Continuing from the same offset would create an endless supply of empty pages. That is a printer feature nobody requested.
Keep the PDF coordinate system consistent
This code creates a Core Graphics PDF context directly. Its ordinary coordinate system has its origin at the bottom left, which is suitable for the Core Text frame. There is no UIKit drawing context to flip.
Don’t copy a translateBy/scaleBy pair from a UIGraphicsPDFRenderer example into this function without accounting for that difference. A transform that fixes one coordinate system can invert another.
Each iteration begins and ends one page. We reset the text matrix before drawing and leave the page transformation unchanged. The page is created only after a valid, nonempty fitted range exists, so a failure to fit the next line isn’t returned as a successful blank page.
Finish the document before returning its bytes
closePDF() completes pending PDF output. It happens before output as Data, not in a defer that runs after the return expression has already been evaluated.
On an error, the context is closed and the function throws. Its partially drawn buffer never becomes the successful return value. The cancellation check runs between pages; it cannot interrupt Core Text halfway through laying out a frame.
To write the completed document, put this second function in the same file:
nonisolated func writeTextReport(_ text: String, to destination: URL) throws {
let pdf = try TextReportPDF.render(text)
try pdf.write(to: destination, options: .atomic)
}
The caller owns the destination URL and any required file access. A successful atomic write replaces an existing file at that destination; this is not a no-overwrite API. The function performs no separate pre-delete. Our document-saving article covers that persistence boundary.
Rendering is synchronous CPU work. Capture the report’s text as a value and run the export from an appropriate background operation in your app, then deliver the completed Data or file to its export UI. nonisolated permits the function to be called outside an actor; it does not move a call off the main thread. Keep mutable view models out of the rendering operation.
Two limits keep this in-memory export small. The exporter checks the 100,000 UTF-16-unit budget before allocating the attributed string. It also stops at 250 pages, since even a short input with many line breaks can produce a large document on shallow paper. Exceeding either budget throws. Set those limits to match the reports your app supports. A much larger report needs a different resource budget and potentially a file-backed output design.
Reopen the result and look for the missing ending
A nonempty Data value does not prove a complete report. Neither does a successful file write.
The sample exports 150 numbered entries and reopens the bytes with PDFKit’s PDFDocument(data:). For each page, it checks the paper size with bounds(for: .mediaBox) and collects the text from PDFPage.string. It then compares the words with the input in order, allowing line breaks to change. A deliberately broken renderer writes only the first page. PDFKit opens that file happily, but the comparison catches the missing entries and final marker.
Useful cases include:
| Case | Expected behavior |
|---|---|
| Short report | One page, all words present |
| Many long paragraphs | Several normal-sized pages, original word order preserved |
| Long unbroken word | Layout makes progress without repeating or skipping the tail |
| Emoji and combining characters before a final marker | UTF-16 cursor reaches the marker; no grapheme-count termination bug |
| Empty or whitespace-only input | Explicit error |
| Input above the example’s length budget | Explicit error, no successful PDF |
| Nonfinite dimensions or a one-point text column | Explicit geometry error |
| Report needs a 251st page | Error before the extra page is drawn |
| Positive geometry too short for one line | No-progress error instead of an infinite loop |
| Task already cancelled at a page boundary | Cancellation error and no returned PDF |
Text extraction is a useful check, not a universal round-trip format. PDFKit may normalize accents, omit formatting characters or extract a complex emoji differently. Keep the original text if your app needs exact Unicode or editable source recovery. Selectable PDF text also isn’t proof of a tagged, accessible PDF with a correct reading order; this sample does not build that structure.
Render and inspect the first, a middle and the last page too. A text assertion won’t catch an upside-down page, poor margins or a font substitution that changes the visual result.
To run the checks yourself, unzip the example on an Apple silicon Mac with Xcode selected, open the TextReportPDF directory in Terminal, and run python3 verify.py. The runner prints the location of its verification report. Its scratch field points to the generated PDFs.
Verification. The exact Swift blocks compile with Xcode 27.2 and Swift 6.4.2 for an iOS 17 deployment target. Ten behavior groups pass on macOS 27.2.1 and the iOS 27.2 simulator under ordinary and MainActor default isolation. The 150-entry fixture produces ten pages with all words in order. The checks include the exact input-budget boundary, saved-file reopening, cancellation and a deliberately incomplete renderer. Rendered first, middle and last pages were inspected on both runtimes. Older operating systems, physical devices and tagged-PDF accessibility were not tested.
This exporter handles one plain-text flow. It deliberately leaves tables, images, headings with keep-together rules and multi-column layout to a document design that actually specifies those behaviors. A small report should end with its last paragraph, not a surprise layout engine.