compose-pdf
A pure-Kotlin Kotlin Multiplatform library that generates vector PDFs whose output is
identical across devices, with selectable/searchable text, small files, automatic
pagination, authored with a Compose-style DSL. Output does not depend on the device
font-scale or the host UI lifecycle.
Coordinates: io.github.rikoappdev:compose-pdf · Targets: Android + iOS + JVM · License: Apache-2.0.
The published artifact bundles no font — you pass your own (see Fonts).
Why a custom engine
To be identical to the dot and vector/searchable at once, no per-platform text engine may
touch layout, and the PDF must contain real text operators with an embedded font (so it can't be
rasterized — and no public Kotlin Multiplatform PDF backend exists for vector output on iOS). So
all layout, text shaping, glyph positioning, TrueType subsetting and PDF serialization run in
shared commonMain integer math (fixed point, in thousandths of a point).
"Identical" = every glyph's (x,y) origin and the extracted Unicode match across platforms
(engineered to exact integer equality). Raw file bytes may differ (compression/float) — invisible
to users.
Features
- Embedded subset Type0/CIDFontType2 (Identity-H) + ToUnicode → selectable & searchable text, including Latin diacritics (composite glyphs subset correctly).
- Compose-style DSL:
text, spacer, divider, row(verticalAlignment) { cell(weight) { } } (a cell(0f) shrinks to its content's width — pair it with a cell(1f) {} spacer to push a logo / info block to an edge; verticalAlignment centres a short cell against a taller one; split = true lets the cells continue across pages), column, box(padding, border, background) (per axis: paddingHorizontal / paddingVertical), keyValue(label, value), image / photoGrid (JPEG /DCTDecode pass-through and PNG — decoded in pure Kotlin to a /FlateDecode image with an /SMask for transparency; PhotoFit.Cover / Contain / Smart — smart preserves aspect but crops extreme strips; align = HorizontalAlignment.Start left-aligns a contained logo in a wide cell; both take a PdfImageSource instead of bytes to keep photo-heavy documents bounded), table (weighted columns, repeating header, total rows, optional zebra striping).
- Vector images (SVG + Android VectorDrawable):
vector(bytes, …) imports both formats (auto-detected) into native, resolution-independent PDF vector paths — the full SVG/VectorDrawable path grammar (incl. elliptical arcs), basic shapes (rect/circle/ellipse/line/poly…), <group>/transform, nonzero & even-odd fill, stroke, per-element opacity, currentColor and the full CSS named-color set. Embedded as a reusable Form XObject, so a logo repeated in a header costs a single object. align (like image) left/center/right-aligns the logo inside its cell. Pure-Kotlin, dependency-free (no XML library).
- Header / footer / page numbers: repeating
header/footer bands and an auto page-number line whose space is reserved (content never overlaps it). Bands can be page-aware: read page.number / page.total / page.isFirst / page.isLast anywhere inside the block ("Page 3 / 12" next to a logo, a different first-page header, a last-page signature row); band height may differ per page, gap sets the band-to-content spacing. PageConfig controls the rest — repeatHeader (every page vs. first page only, like a title block), pageNumberFormat, pageNumberStyle, pageNumbers. See Page-aware header & footer.
- Familiar value types:
TextStyle (with copy), PdfColor/Color(0xFF…), Dp/.dp, Sp/.sp, FontWeight (Normal, Medium, Bold), TextAlign.
- Fractional units & per-side margins:
0.75.dp, 14.6.dp, 7.5.sp are honored to 0.001 pt, and PageConfig(margins = PageMargins(all = 36.dp, bottom = 14.6.dp)) sets each page margin separately — see Fractional units & page margins.
- Medium weight:
FontWeight.Medium with an optional third face (mediumFontBytes); without it Medium text uses the Regular face — see Medium weight.
- Automatic pagination: paragraphs split by line; tables split by row (repeating the header); bordered boxes and columns split across pages with the border/background redrawn per fragment; images and rows move whole, unless a row is marked
row(split = true) — then its cells continue across pages side by side. Keep-together moves a block whole instead of leaving a sliver, for the whole document or per box / split row (keepTogether). A box can repeat a continuation header at the top of every page it continues on, and a row taller than a page is split instead of running into the footer. See Long content.
- Color emoji: pass an optional emoji font (
render(regular, bold, emoji)) and emoji render as inline color bitmaps from sbix / CBLC+CBDT faces (the "phone" look) — see Color emoji. Opt-in; omit it and output is unchanged.
- Progress reporting:
render(regular, bold, onProgress = { … }) calls the optional onProgress: (Float) -> Unit with 0f→1f as pages are laid out and serialized — drive a real determinate progress bar. Omit it and output is byte-for-byte unchanged.
- Unbounded documents:
image/photoGrid take a PdfImageSource ({ File(path).readBytes() }) so JPEG photos are pulled one at a time and released, and renderTo(sink, regular, bold) writes the byte-for-byte identical PDF straight into a PdfSink instead of returning one array. Neither the photos nor the finished file ever exist whole — a measured 397 MB, 870-photo report streams in a 64 MiB heap, the case that OOMs photo-heavy exports on Android's default heap. image(bytes) stays for logos and small documents.
- FlateDecode compression: content streams, the subset font program and the ToUnicode CMap are deflated by a pure-Kotlin encoder (deterministic on every platform).
- Regular + Bold faces (bundled), plus an optional Medium face you supply.
val pdf: ByteArray = pdfDocument(PageConfig(margin = 36.dp)) {
header { row { cell(1f) { text("ACME Inc.", TextStyle(fontSize = 10.sp, fontWeight = FontWeight.Bold)) } }; divider() }
text("Report", TextStyle(fontSize = 18.sp, fontWeight = FontWeight.Bold))
table(columns = listOf(PdfColumn(3f, "Item"), PdfColumn(1f, "Qty", TextAlign.End))) {
row("Item A", "3"); row("Item B", "7"); totalRow("Total", "10")
}
photoGrid(jpegBytesList, perRow = 3, cellHeight = 80.dp)
}.render(regularFontBytes, boldFontBytes)
Page-aware header & footer
A header { } / footer { } block that never touches page is built once and is identical on every
page. Reading page anywhere inside the block (nested row / cell / box included) makes the band
page-aware: it is rebuilt for each page once the total is known.
// titleBlock() / runningHeader() are your own ContainerScope helpers; logoSvgBytes is your logo's SVG bytes.
val doc = pdfDocument(PageConfig(margin = 36.dp, pageNumbers = false)) {
header { if (page.isFirst) titleBlock() else runningHeader() }
footer(gap = 12.dp) {
divider()
row(verticalAlignment = VerticalAlignment.Center) {
cell(1f) { text("Contoso Field Reports"); text("Prepared by the field team") }
cell(0f) { text("Report ID 12345 · Page ${page.number} / ${page.total}") }
cell(0f) { vector(logoSvgBytes, width = 48.dp, height = 14.dp) }
}
}
// ... body ...
}
page is a PageInfo: number (1-based), total, isFirst, isLast; user code always sees 1 <= number <= total.
- Band height may differ per page; content never overlaps a band. A page-aware band that adds nothing on a
page (e.g.
if (page.isFirst) ...) takes no space there. repeatHeader = false still means page 1 only.
- The lambda may run several times (once at build, then per page), with provisional totals while
pagination settles - only the final pass is drawn - so keep it free of side effects.
- A logo (raster or vector) is embedded once, not once per page - also when the same instance sits in a static
header and a page-aware footer. Hoist its bytes /
PdfImageSource out of
the lambda so it is not re-read; the dedupe registry keeps the bytes of each distinct band image during layout.
- Set
PageConfig.pageNumbers = false when you draw the numbers yourself. gap (default 12 dp, not negative)
is the spacing between the band and the content.
- Reusable band helpers: write them as
fun ContainerScope.pageLabel(page: PageInfo) { ... } and call
pageLabel(page) - that works at any depth. A fun BandScope.pageLabel() extension called inside a nested
cell { } / column { } / box { } resolves against the band, not the cell, so its content escapes the
cell; call BandScope extensions only at the top level of the band block.
- Inside
header/footer blocks a member or top-level symbol of your own named page is shadowed by
BandScope.page; locals and parameters named page still win (and a band that then never reads
BandScope.page stays static).
Fractional units & page margins
Dp and Sp carry fractional values, and the page margin can differ per side:
val doc = pdfDocument(
PageConfig(margins = PageMargins(horizontal = 40.dp, top = 36.dp, bottom = 14.6.dp)),
) {
header { text("Example Ltd.", TextStyle(fontSize = 7.5.sp)) }
footer { divider(thickness = 0.75.dp); text("example.com", TextStyle(fontSize = 7.5.sp)) }
// ... body ...
}
- Fractional values.
0.75.dp, 14.6.dp, 7.5.sp work next to whole ones (8.sp, 12.dp). Lengths you
give (margins, spacers, dividers, paddings, gaps, borders, radii, image/vector boxes, font sizes) are honored
to 0.001 pt, with no float drift (four 2.5.dp spacers add up to exactly 10 pt). Dp.value / Sp.value are Float.
- Rounding rule. Quantities the engine derives are still rounded to whole points, exactly as before: text
widths and ascent, line height (
floor(fontSize x lineHeightMultiple)), centring offsets, weighted row / column
widths, intrinsic image width. Images and vectors fitted into a box with a fractional side, and rounded corners
with a fractional radius, are placed to 0.001 pt. A document that uses only whole values renders
byte-for-byte as in 0.10.0. A Dp / Sp must be finite and within ±1,000,000.
PageMargins (start, top, end, bottom, each >= 0) cascades like Compose paddings:
all (default 36 dp) -> horizontal / vertical -> start / top / end / bottom. start is the left
and end the right edge (PDF has no RTL). PageConfig.margin stays as the all-sides shorthand; when margins
is passed it wins.
- Where it applies. The body starts at
start and is page width - start - end wide. The header's top edge
sits on the top margin, the footer's bottom edge (or the page-number line, when on) on the bottom margin, and the
body gets whatever is left on each page - measured per page, also for page-aware bands.
The page-number label is aligned (pageNumberStyle.align, centred by default) within the content width.
Long content: split rows, keep-together, continuation headers
A long card (a bordered box with a title bar and two columns of lines) can run across pages: the columns
continue independently, every continuation page starts with the card's title marked "(continued)", and a card
that fits on a page still moves whole to the next one.
fun ContainerScope.card(title: String, left: List<Pair<String, String>>, right: List<Pair<String, String>>) {
val bold = TextStyle(fontSize = 9.sp, fontWeight = FontWeight.Bold)
val bar = Color(0xFFF1F3F5)
box(
border = 1.dp,
cornerRadius = 6.dp,
// Drawn at the top of every page the card continues on (never on its first page).
continuationHeader = { box(padding = 8.dp, background = bar) { text("$title (continued)", bold) } },
) {
box(padding = 8.dp, background = bar) { text(title, bold) }
// keepTogether = false: start right below the title bar instead of moving to the next page.
box(paddingHorizontal = 12.dp, paddingVertical = 8.dp, keepTogether = false) {
// split = true: both columns continue on the next page, each on its own.
row(gap = 16.dp, split = true, keepTogether = false) {
cell(1f) { left.forEach { (label, value) -> keyValue(label, value) } }
cell(1f) { right.forEach { (label, value) -> keyValue(label, value) } }
}
}
}
}