AOT

Inside the .fpaot Compiler: Text Reflow Without a Browser

How ForkPDF compiles observed layouts into plates, plans, and a fail-closed text runtime that reflows changed strings without a browser.

· 10 min read · 2,208 words · ForkPDF Engineering

.fpaot is not a PDF with named holes. It is a compiled document model.

Every developer who reads the AOT preview asks the same question: if there is no Chromium at runtime, how is this not brittle pdf-lib string replacement? The short answer is that the compiler does not store strings at fixed coordinates. It stores text-free page plates, observed page plans, and a text runtime locked to the renderer’s font advances and line breaks. At runtime, a changed string is measured, matched to an observed content profile, and drawn. If no profile matches, generation fails closed.

That refusal is the feature.

The wrong mental model: a PDF with holes

A template-and-overlay system treats the PDF as a form. It draws the background, then places each value at an (x, y) coordinate with a fixed font size. That works until a value changes length.

An invoice line item is a good test. Change “Brand strategy” to “Brand strategy and positioning for the spring launch” and three things can break at once:

  • The description needs a second line, but the row height was fixed by the background.
  • The row below does not move, so the detail and amount collide.
  • The totals block still assumes the original page count.

A general-purpose layout engine solves this by reflowing the document. AOT solves it by compiling the layout decisions the browser already made, then reproducing those decisions for payloads inside a declared envelope.

What the compiler consumes

The compiler does not run Chromium. The ForkPDF API does that during corpus observation. Each render produces two inputs:

  • The settled PDF.
  • A spatial data.pb payload in schema v2.

The spatial payload is the important half. It contains box metrics, resolved text styles, line fragments, shaped runs, break opportunities, and the physical page each fragment landed on. The compiler reads those measurements directly instead of reconstructing them from the PDF.

The invoice example is a 72-shape corpus:

Text
18 item counts (1–18)
× project description at 1 or 2 lines
× notes at 1 or 2 lines
= 72 payloads

Those 72 observations become 72 plans. The bundle also contains 268 plate PDFs and a renderer-exact text runtime. The checked-in Atelier bundle is 7.7 MB.

The API is a compile-time dependency. It is not in the request path.

Plates: subtract text, keep the page

A plate is the part of a page that does not change: rules, fills, logos, static images, table borders, and other background graphics. Text is removed before the plate is built.

The current pipeline is self-contained:

Text
settled PDF
  -> PDF.js text geometry -> slots and observed line models
  -> PDF.js vector/raster render with text paint operations skipped
  -> dynamic image rectangles cleared
  -> background PNG or validated vector plate
  -> pdf-lib plate PDF
  -> deterministic /Artifact wrapper

The default hybrid mode first tries to replay supported PDF operators into a compact vector plate. It rasterizes that candidate and compares it with the PDF.js reference. A vector plate is kept only when it stays inside the fidelity and size budgets: 1.5% maximum pixel difference, 3 mean absolute error, and at least a 50% size saving. Pages with static images, complex soft masks, shading, or unsupported operators fall back to a deterministic raster plate at 150 DPI. Static images can stay in the plate. Dynamic images are cleared and redrawn by the runtime.

This is where the 0.3.0 compiler differs from the first version. The original plate pipeline shelled out to Inkscape and Poppler. It worked, but it made builds depend on native binaries and system fonts. The current compiler ships PDF.js and @napi-rs/canvas, so a compile can run without external PDF tools, provided Node.js 22.13+ and a supported @napi-rs/canvas platform. Inkscape, Poppler, and system fonts are not required.

The invoice example produces 268 plate PDFs. That number is corpus-specific: it comes from 72 observed shapes, one- and two-page layouts, and page-level backgrounds. It is not a universal bundle size or a fixed plate count.

A five-item invoice generated offline by the compiled AOT bundle

A five-item invoice generated from the compiled bundle. The live AOT page has the API-versus-AOT slider.

Plans: the decisions, not just the pixels

A plan is the page skeleton for one observed payload. It records the page count, the plate for each page, the slots the runtime must draw, and the content profile the payload belongs to.

The bundle uses lazy metadata packs and shared chunks, so 72 plans do not mean 72 copies of the same template. Plans reference the data they need; slots share glyph and string storage. This is also why the .fpaot container is not a zip of PDFs. It is a content-addressed bundle with its own index, chunk dictionary, and deterministic metadata.

At generation time the runtime chooses a plan first. It does not pick a nearby plan and hope. If the item count or page structure was never observed, the generation stops:

JSON
{
  "ok": false,
  "code": "E_MISSING_PLAN",
  "message": "No observed plan for 19 items",
  "required": {
    "items": 19,
    "minimumPages": 2,
    "maximumPages": 5,
    "candidates": []
  }
}

The error includes a render request. Add a 19-item payload to the corpus, recompile, and the shape becomes part of the bundle.

The text runtime: measure before drawing

A plan tells the runtime where a slot lives. It does not tell the runtime how wide a new string will be. That is the job of the text runtime.

The compiler extracts the original font assets from the source render, records the Fontkit shaper identity, and retains renderer-produced Type3 procedures for every reachable glyph, face, feature set, and font size. It then solves per-glyph and per-pair advances from the authoritative ShapedRun.advance_css_px totals in the spatial payload. Observed totals are retained per string and letter-spacing value. Before the lock is written, every matching advance is converted through its page transform and checked against the exact runtime within 0.01 pt.

The compiler also records observed line breaks. A slot’s breakModel contains the lines the browser produced, the wrapping mode, and the space advance. That is enough to reproduce the observed line layout without shipping a browser text-shaping stack.

The missing piece is a way to decide whether a new string fits an observed layout. AOT calls this a content profile. The profile is a signature of line counts across the variable slots, plus a field signature for structured rows. For an invoice item, a profile can look like this:

JSON
{
  "description": 1,
  "detail": 1,
  "qty": 1,
  "rate": 1
}

At runtime the sequence is:

  1. Measure the incoming strings with the locked font advances.
  2. Derive the content profile signature.
  3. Select an observed plan and plate that support that profile.
  4. Run the compiled testcase to settle pagination and computed values.
  5. Draw the text into the plate slots.

If step 2 produces a profile that was never compiled, the runtime does not guess. It returns E_CONTENT_PROFILE_NOT_FOUND. The response below is trimmed for readability; the required.contentProfile and renderRequests fields are the parts that matter:

JSON
{
  "ok": false,
  "code": "E_CONTENT_PROFILE_NOT_FOUND",
  "message": "Payload content does not fit any compiled content profile",
  "required": {
    "maxWidth": 250.5,
    "width": 269.02,
    "contentProfile": {
      "signature": [2],
      "fieldSignature": [
        { "description": 2, "detail": 1, "rate": 1 }
      ],
      "availableProfiles": [
        { "description": 1, "detail": 1, "qty": 1, "rate": 1 },
        { "description": 1, "detail": 1, "rate": 1 }
      ]
    }
  },
  "renderRequests": [
    { "reason": "content_profile" }
  ]
}

The message is precise: this payload needs a two-line description, but the bundle only has one-line description profiles. The fix is not to shrink the font or clip the text. The fix is to add one corpus render with a two-line description and recompile.

The runtime exposes the same decision in code:

JavaScript
import { loadCompiled } from 'forkpdf-aot/runtime';

const runtime = loadCompiled('template.fpaot');
const result = await runtime.generate(payload);

if (!result.ok && result.code === 'E_CONTENT_PROFILE_NOT_FOUND') {
  console.error(result.required.contentProfile.signature); // [2]
  console.error(result.required.contentProfile.availableProfiles);
}

That error is also a routing signal. A production system can catch E_CONTENT_PROFILE_NOT_FOUND, send the payload to the Cloud API, and keep the AOT path for the covered share.

What reflows, what refuses

The supported envelope is deliberately narrow. The example bundle accepts:

  • 1–18 line items.
  • One-line item descriptions and details.
  • Project descriptions and notes at one or two lines.
  • Changed client names, invoice numbers, dates, item text, rates, amounts, and totals.
  • One-page and two-page layouts.

It refuses:

  • 19 or more line items.
  • Item details that need a second line.
  • Project descriptions or notes that need three or more lines.
  • Long unbroken tokens that overflow their slot.
  • Content-dependent widths, floats, justification, automatic hyphenation, RTL or vertical writing, and multi-item inline formatting.

Unchanged text replays the authoritative line fragments from the spatial payload. Changed text is measured and matched. When the match fails, the PDF is not delivered with a silent overflow.

This is the difference between a template wrapper and a compiler. A wrapper always produces a file. A compiler can reject an input that is outside its declared envelope.

Source-free, not exact replay

It is tempting to compile the observed PDFs and replay them byte-for-byte for known inputs. AOT 0.3.0 does not do that for new bundles.

New bundles render both trained and changed payloads structurally. The manifest sets exactReplay: false, the bundle stores pb-skeletons instead of raw source PDFs and PBs, and every generation executes the compiled testcase. Legacy bundles that contain an exact map remain loadable with useExactMap: true; new bundles ignore that option.

This costs a small amount of generation work and buys three things:

  • Changed inputs follow the same path as trained inputs, so the text runtime is exercised constantly.
  • The bundle does not carry raw customer documents.
  • The output is rebuilt from the compiled model rather than copied from a previous render.

Compliance is locked to the same model. A bundle compiled for PDF/UA-2 + PDF/A-4 cannot be downgraded at runtime. A request for a different profile fails with E_COMPLIANCE_LOCKED. The compiler validates source renders and structural output with veraPDF when the bundle is compliance-locked; the checked-in invoice bundle passes 5/5 sampled Worker PDFs for PDF/UA-2 + PDF/A-4.

What the compiler cannot do

AOT is not a faster URL-to-PDF endpoint. It is a compiler for document families with a measurable variation set.

Closed sets — certificates, payslips, tickets, event badges, fixed-format labels — can be compiled exhaustively and covered 100% within the declared set. Variable mixes — invoices with free-form line items, statements with variable notes — need a measured sample and an API fallback for misses. Unbounded or user-authored layouts should stay on the Cloud API.

The invoice example is honest about its boundary: 1–18 one-line items, project and notes at one or two lines, one- and two-page layouts. A 19-item payload is not “almost covered.” It is refused with E_MISSING_PLAN.

Verification and numbers

The checked-in Atelier bundle regenerates 72/72 payloads offline: 28 one-page layouts and 44 two-page layouts. The bundle contains 72 plans and 268 plate PDFs across 604 entries.

The Cloudflare Workers benchmark on the AOT page uses a deployed Worker, Workers Paid, and the Delhi (DEL) colo:

Shape Warm PDF-ready p50 Warm PDF-ready p95 Full PDF p50 PDF size
1 page · 5 items 269 ms 414 ms 383 ms 2.82 MB
1 page · 7 items 260 ms 447 ms 356 ms 2.82 MB
2 pages · 12 items 378 ms 603 ms 493 ms 3.26 MB
2 pages · 18 items 425 ms 664 ms 547 ms 3.26 MB

Cold first request after a fresh version: 1.95 s p50. The first request immediately after deploy was 3.8 s, including a 1.76 s bundle asset pull. These numbers are from one colo and are not a global guarantee. PDF-ready time includes network latency plus generation; full-PDF time includes transferring the file.

The bundle is 7.7 MB for this example and compliance profile. The PDF size is dominated by embedded Type3 glyph procedures, not by compliance metadata.

The takeaway

A compiler is defined by what it refuses.

.fpaot does not pretend that every HTML document can be generated without a browser. It compiles a declared document family, locks the font metrics and observed line breaks, and refuses payloads outside the observed envelope. That is why a changed invoice line can reflow correctly without Chromium — and why an unobserved three-line note returns an error instead of a broken PDF.

If you want to inspect the output, the AOT page has the API-versus-AOT slider, the 72-shape coverage table, and the Worker benchmark. The compiler and runtime are MIT-licensed preview packages: forkpdf-aot-compiler and forkpdf-aot. The Atelier repository contains the bundle, the payloads, and the offline verifier.

For the underlying spatial data model, see Spatial Queries. For the compliance profiles, see the capability matrix. If you are weighing AOT against a browser fleet, the Puppeteer and Playwright comparison covers the operational trade-offs.

ForkPDF Engineering

ForkPDF is an HTML-to-PDF API with spatial layout introspection, self-healing layout tests, and PDF/A and PDF/UA output. The blog is written and reviewed by the ForkPDF team.

About the author →

Try the ForkPDF API

Generate a PDF, inspect every element's page and coordinates, and return a layout patch — in one API call.

100 free credits. No credit card required.