@rentnerkev/pdf 0.1.1 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -4
- package/dist/ai.d.ts +53 -0
- package/dist/ai.d.ts.map +1 -0
- package/dist/ai.js +139 -0
- package/dist/ai.js.map +1 -0
- package/dist/native/rentnerpdf.linux-arm64-gnu.node +0 -0
- package/dist/native/rentnerpdf.linux-arm64-musl.node +0 -0
- package/dist/native/rentnerpdf.linux-x64-gnu.node +0 -0
- package/dist/native/rentnerpdf.linux-x64-musl.node +0 -0
- package/dist/native/rentnerpdf.win32-arm64-msvc.node +0 -0
- package/dist/native/rentnerpdf.win32-x64-msvc.node +0 -0
- package/dist/wasm/pkg/rentnerpdf_wasm_bg.wasm +0 -0
- package/docs/usage.md +1604 -0
- package/package.json +6 -1
package/docs/usage.md
ADDED
|
@@ -0,0 +1,1604 @@
|
|
|
1
|
+
# Usage guide
|
|
2
|
+
|
|
3
|
+
How to build PDFs with RentnerPDF from TypeScript and React. Coming from another library? Read the guide for [React-PDF](migrating-from-react-pdf.md), [pdfmake](migrating-from-pdfmake.md) or [PDFKit](migrating-from-pdfkit.md) next to this one. Framework setups (Node.js, Bun, TanStack Start, Next.js) are in the [recipes](recipes/README.md).
|
|
4
|
+
|
|
5
|
+
> [!IMPORTANT]
|
|
6
|
+
> RentnerPDF `1.0.0` establishes the stable TypeScript API and [IR v1 contract](#ir-versioning).
|
|
7
|
+
|
|
8
|
+
> [!NOTE]
|
|
9
|
+
> **Experimental** parts are exempt from SemVer in 1.x until promoted and may change in a minor release. They include `@rentnerkev/pdf/worker` (API and protocol), `usePdf()` and `<PdfPreview>`, `@rentnerkev/pdf/vite`, `renderToStream()` and the optional Dutch hyphenation patterns (the Rust feature `hyphenation-dutch`).
|
|
10
|
+
|
|
11
|
+
Every TypeScript example in this guide is a region of a file in [`web/src/tests/docs/`](../web/src/tests/docs/), type-checked and rendered by `bun test`.
|
|
12
|
+
|
|
13
|
+
## Contents
|
|
14
|
+
|
|
15
|
+
- [Install](#install)
|
|
16
|
+
- [Compatibility](#compatibility): runtimes, platforms, frameworks and what CI checks
|
|
17
|
+
- [IR versioning](#ir-versioning)
|
|
18
|
+
- [Quick start](#quick-start)
|
|
19
|
+
- [Authoring paths](#authoring-paths): own JSX runtime, React, factories
|
|
20
|
+
- [Engine](#engine): options, backends, cancellation, batches, streams, fonts at run time, closing
|
|
21
|
+
- [Components](#components): document, pages, boxes, text, page flow
|
|
22
|
+
- [Styling](#styling): `className`, `style`, themes, editor support
|
|
23
|
+
- [Tables](#tables): element tables and data tables
|
|
24
|
+
- [Page templates and placeholders](#page-templates-and-placeholders): headers, footers, page numbers, letterheads
|
|
25
|
+
- [Images, SVG, links and bookmarks](#images-svg-links-and-bookmarks)
|
|
26
|
+
- [Languages, scripts and typography](#languages-scripts-and-typography): fonts, right-to-left, hyphenation, justification
|
|
27
|
+
- [PDF/A and attachments](#pdfa-and-attachments): archiving, e-invoices
|
|
28
|
+
- [Accessibility](#accessibility): tagged PDF and PDF/UA-1
|
|
29
|
+
- [Browser preview](#browser-preview): Web Worker, `usePdf()`, `<PdfPreview>`
|
|
30
|
+
- [Errors, warnings and diagnostics](#errors-warnings-and-diagnostics)
|
|
31
|
+
- [Limits](#limits): resource limits and what is not supported yet
|
|
32
|
+
- [Performance](#performance)
|
|
33
|
+
- [Playground](#playground)
|
|
34
|
+
- [Local documentation for tools](#local-documentation-for-tools): `@rentnerkev/pdf/ai` for AI agents and scripts
|
|
35
|
+
|
|
36
|
+
## Install
|
|
37
|
+
|
|
38
|
+
Requirements: Node.js 22.14+ or Bun 1.4+; React 19 only for `@rentnerkev/pdf/react`. What is tested where: [Compatibility](#compatibility).
|
|
39
|
+
|
|
40
|
+
Install the published package with `npm install @rentnerkev/pdf` (or `bun add @rentnerkev/pdf`). It bundles the native engines for Windows and Linux on x64 and ARM64, including glibc and musl on Linux, and the WebAssembly engine. `backend: 'auto'` loads the matching native binary or falls back to WebAssembly, including on macOS.
|
|
41
|
+
|
|
42
|
+
For a source checkout, install the [development requirements](../README.md#development) and build the engines you need.
|
|
43
|
+
|
|
44
|
+
```sh
|
|
45
|
+
bun install --frozen-lockfile
|
|
46
|
+
bun run build:native # native engine on supported Windows and Linux hosts
|
|
47
|
+
bun run build:wasm # WebAssembly engine, including on macOS
|
|
48
|
+
bun run pack:packages # TypeScript build and one tarball with the built engines
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Install the tarball from `packages/tarballs/` in your project.
|
|
52
|
+
|
|
53
|
+
```sh
|
|
54
|
+
bun add <clone>/packages/tarballs/rentnerkev-pdf-1.0.1.tgz
|
|
55
|
+
npm install <clone>/packages/tarballs/rentnerkev-pdf-1.0.1.tgz
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
The release matrix supplies all six native builds and WebAssembly. A local tarball only includes the engines built from that checkout. `createEngine()` checks that the selected engine can read the IR version the TypeScript API writes.
|
|
59
|
+
|
|
60
|
+
## Compatibility
|
|
61
|
+
|
|
62
|
+
What runs where and what the repository's CI checks for it, on every pull request that touches the code (`ci.yml`, `platforms.yml`, `rendering.yml`, `standards.yml`). "Locally" means checked by hand for a recipe, not in CI.
|
|
63
|
+
|
|
64
|
+
### Runtimes
|
|
65
|
+
|
|
66
|
+
| Runtime | Engine | Status | Checked in CI |
|
|
67
|
+
| --------------------------------- | ------------------------------------------------- | -------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
68
|
+
| Node.js 22.14+ | Native; WebAssembly where no native package loads | Supported | Node.js 24: installs of the packed packages on all six native targets and of the WebAssembly package, the React smoke test, the TanStack Start `node-server` output. Node.js 22 and 26 do not run in CI |
|
|
69
|
+
| Bun 1.4+ | Native; WebAssembly where no native package loads | Supported | Bun 1.4.5: the whole test suite (Linux x64), installs on glibc Linux and Windows (x64, arm64), the TanStack Start `bun` output and `vite dev`. Not on musl |
|
|
70
|
+
| Browsers | WebAssembly in a Web Worker | Preview helpers; the bundler setup is manual ([details](#browser-preview)) | No browser runs: the worker protocol is tested over a `MessageChannel` and in a Bun `Worker`, `@rentnerkev/pdf/worker` is bundled for browsers without React or the native addon, and the packed WebAssembly package renders through the worker protocol |
|
|
71
|
+
| Deno | – | Not tested | – |
|
|
72
|
+
| Cloudflare Workers, edge runtimes | – | Not supported yet ([recipe](recipes/cloudflare-workers.md)) | – |
|
|
73
|
+
|
|
74
|
+
### Platforms
|
|
75
|
+
|
|
76
|
+
| Engine | Built in CI on | Installed and loaded in CI on | Package managers in CI |
|
|
77
|
+
| ------------------ | -------------------------------------------------- | -------------------------------------- | ---------------------- |
|
|
78
|
+
| `win32-x64-msvc` | `windows-latest` | `windows-latest` | npm, pnpm, Yarn, Bun |
|
|
79
|
+
| `win32-arm64-msvc` | `windows-latest` (cross-compiled) | `windows-11-arm` | npm, pnpm, Yarn, Bun |
|
|
80
|
+
| `linux-x64-gnu` | `ubuntu-latest`, glibc 2.17 floor | `ubuntu-latest` | npm, pnpm, Yarn, Bun |
|
|
81
|
+
| `linux-arm64-gnu` | `ubuntu-latest` (cross-compiled), glibc 2.17 floor | `ubuntu-24.04-arm` | npm, pnpm, Yarn, Bun |
|
|
82
|
+
| `linux-x64-musl` | `ubuntu-latest` (cargo-zigbuild) | `node:24-alpine` container | npm, pnpm (Node.js) |
|
|
83
|
+
| `linux-arm64-musl` | `ubuntu-latest` (cargo-zigbuild) | `node:24-alpine` on `ubuntu-24.04-arm` | npm, pnpm (Node.js) |
|
|
84
|
+
| WebAssembly | `ubuntu-latest` | `ubuntu-latest`, rendering a PDF | npm, pnpm, Yarn, Bun |
|
|
85
|
+
|
|
86
|
+
- **macOS** uses the bundled WebAssembly engine with `backend: 'auto'`. The project has no macOS CI job.
|
|
87
|
+
- **Rendering:** each native consumer job renders a smoke PDF on its target platform. The Rust snapshot, visual and determinism suites run on Linux x64 and Windows x64, whose corpus PDFs must be byte-identical. The TanStack Start check renders its PDF route on both. Parity tests check that the WebAssembly engine renders the corpus to the same bytes as the native one.
|
|
88
|
+
- **Output:** the corpus rendered as PDF/A-3b and as PDF/UA-1 passes veraPDF 1.30.4, and the [ZUGFeRD recipe](recipes/zugferd.md)'s invoice passes Mustang 2.26.0 (Linux). PDF viewers are not checked automatically.
|
|
89
|
+
- **Package managers:** pnpm 12 and Yarn 4 in CI.
|
|
90
|
+
|
|
91
|
+
### Frameworks and libraries
|
|
92
|
+
|
|
93
|
+
| Framework or library | Setup | Checked |
|
|
94
|
+
| --------------------------------------------------------------- | --------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
95
|
+
| React 19 (`@rentnerkev/pdf/react`) | Optional peer dependency | CI: React 19.0.0, the latest release and the canary channel, each with React's development and production builds, in Bun and in a Node.js 24 smoke test |
|
|
96
|
+
| TanStack Start (Vite, Nitro) | `rentnerPdf()` from `@rentnerkev/pdf/vite` | CI on Linux x64 and Windows x64 with TanStack Start 1.169.7, Vite 8.3.8 and Nitro 3.0.261103-rc: builds with the `node-server` and `bun` presets run away from the project and answer the PDF route, the client bundle holds no engine code, `vite dev` renders ([recipe](recipes/tanstack-start.md)) |
|
|
97
|
+
| Other Vite and Nitro apps | `rentnerPdf()` | The plugin's unit tests and the TanStack Start check |
|
|
98
|
+
| Next.js 16 | `serverExternalPackages: ['@rentnerkev/pdf']` | Locally: Next.js 16.4.6 on Windows ([recipe](recipes/nextjs.md)) |
|
|
99
|
+
| `node:http`, Express 5, Fastify 5, Hono 4, `Bun.serve` | None | Locally: Windows, Node.js 25 and Bun 1.4.5 ([recipe](recipes/node-and-bun.md)) |
|
|
100
|
+
| Tailwind CSS 4, `clsx`, `tailwind-merge` 3 | [Editor support](#editor-support) | CI: the [support matrix](tailwind-support.md) covers every class of Tailwind CSS 4.3.5; theme reading and `tailwind-merge` 3.7.1 in the test suite |
|
|
101
|
+
| Cloudflare Workers, Next.js' edge runtime, Nitro's edge presets | – | Not supported yet |
|
|
102
|
+
|
|
103
|
+
## IR versioning
|
|
104
|
+
|
|
105
|
+
TypeScript and the native and WebAssembly engines use IR version `1`. The `v` field is required and must be a non-negative integer. Engines report an unsupported version as `INVALID_DOCUMENT` at `v` before inspecting other fields. `createEngine()` checks the binding's IR version before rendering.
|
|
106
|
+
|
|
107
|
+
Within a version, unknown fields, node kinds and closed enum values are `INVALID_DOCUMENT` errors. Open sets such as Tailwind classes and CSS values use the documented warnings. Writers omit unset fields. IR v1 accepts `null` only for `header`, `footer` and `letterhead` on page variants, where it clears an inherited region.
|
|
108
|
+
|
|
109
|
+
Minor releases can add optional fields or values while preserving the decoding and output of documents that use existing features. Producers that use a new field or value need an engine that understands it. Removing or renaming fields, changing defaults or units, or changing the asset or channel layout requires a new major IR version. A field or value slated for removal is documented and deprecated for at least one minor release first.
|
|
110
|
+
|
|
111
|
+
Numbers are finite JSON numbers and integers stay within the JavaScript safe-integer range. Asset indices and columnar channel encodings belong to the IR version. React's markup and the Web Worker message protocol have their own compatibility rules.
|
|
112
|
+
|
|
113
|
+
## Quick start
|
|
114
|
+
|
|
115
|
+
<!-- snippet: web/src/tests/docs/usage/quick-start.tsx#quick-start -->
|
|
116
|
+
|
|
117
|
+
```tsx
|
|
118
|
+
/** @jsxImportSource @rentnerkev/pdf */
|
|
119
|
+
import { writeFile } from 'node:fs/promises'
|
|
120
|
+
import { Document, Page, render, Text, View } from '@rentnerkev/pdf'
|
|
121
|
+
|
|
122
|
+
function Invoice({ number, total }: { number: string; total: string }) {
|
|
123
|
+
return (
|
|
124
|
+
<Document title={`Invoice ${number}`} lang="en">
|
|
125
|
+
<Page size="A4" className="p-page text-sm">
|
|
126
|
+
<View className="mb-8 flex justify-between">
|
|
127
|
+
<Text role="h1" className="text-2xl font-bold">
|
|
128
|
+
Invoice {number}
|
|
129
|
+
</Text>
|
|
130
|
+
<Text className="text-gray-500">Muster GmbH</Text>
|
|
131
|
+
</View>
|
|
132
|
+
<Text>Total: {total}</Text>
|
|
133
|
+
</Page>
|
|
134
|
+
</Document>
|
|
135
|
+
)
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const pdf = await render(<Invoice number="2026-001" total="1.234,56 €" />)
|
|
139
|
+
await writeFile('invoice.pdf', pdf)
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
Text sizes, spacing and colors are Tailwind CSS v4 utilities; `p-page` is RentnerPDF's 20 mm page padding token. The bundled Noto Sans family is the default font.
|
|
143
|
+
|
|
144
|
+
## Authoring paths
|
|
145
|
+
|
|
146
|
+
| Path | Use it for | Imports |
|
|
147
|
+
| ------------------------------------------------------ | -------------------------------------------------------------- | ------------------------------------------------------ |
|
|
148
|
+
| Own JSX runtime (`jsxImportSource: '@rentnerkev/pdf'`) | Node.js/Bun services without React; fastest, zero dependencies | `@rentnerkev/pdf` |
|
|
149
|
+
| React (`@rentnerkev/pdf/react`) | React projects: hooks, context, `use()`, the app's JSX setup | `@rentnerkev/pdf/react` + engine from the main package |
|
|
150
|
+
| Factories (`document()`, `page()`, `view()`, …) | Generated documents, tools, tests; what both JSX paths build | `@rentnerkev/pdf` |
|
|
151
|
+
|
|
152
|
+
Both JSX paths use the same component names and props and render byte-identical PDFs, so switching is an import change.
|
|
153
|
+
|
|
154
|
+
### Own JSX runtime
|
|
155
|
+
|
|
156
|
+
Per file, put `/** @jsxImportSource @rentnerkev/pdf */` first (as in the quick start). For a folder of PDF components, give it a tsconfig:
|
|
157
|
+
|
|
158
|
+
```json
|
|
159
|
+
{
|
|
160
|
+
"extends": "../../tsconfig.json",
|
|
161
|
+
"compilerOptions": {
|
|
162
|
+
"jsx": "react-jsx",
|
|
163
|
+
"jsxImportSource": "@rentnerkev/pdf"
|
|
164
|
+
},
|
|
165
|
+
"include": ["."]
|
|
166
|
+
}
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
- Components run inside `render()`, so they may be `async` and load their data.
|
|
170
|
+
- `createContext()`/`useContext()` work like React's; in an `async` component, read context before the first `await`.
|
|
171
|
+
- The development runtime (`"jsx": "react-jsxdev"`, Bun's default) records where each element was written; errors and warnings then name the file and line.
|
|
172
|
+
- `Fragment`, keys (accepted and ignored) and components returning strings or numbers inside `Text` work as in React. Hooks other than `useContext` do not exist here: use React for them.
|
|
173
|
+
|
|
174
|
+
### React
|
|
175
|
+
|
|
176
|
+
<!-- snippet: web/src/tests/docs/usage/react.tsx#render -->
|
|
177
|
+
|
|
178
|
+
```tsx
|
|
179
|
+
import { createContext, use, useContext } from 'react'
|
|
180
|
+
import { createEngine, type TableColumn } from '@rentnerkev/pdf'
|
|
181
|
+
import {
|
|
182
|
+
Document,
|
|
183
|
+
Page,
|
|
184
|
+
PageNumber,
|
|
185
|
+
renderToPdf,
|
|
186
|
+
Table,
|
|
187
|
+
Text,
|
|
188
|
+
TotalPages,
|
|
189
|
+
} from '@rentnerkev/pdf/react'
|
|
190
|
+
|
|
191
|
+
interface Item {
|
|
192
|
+
readonly name: string
|
|
193
|
+
readonly cents: number
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
interface InvoiceData {
|
|
197
|
+
readonly number: string
|
|
198
|
+
readonly items: readonly Item[]
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const engine = await createEngine()
|
|
202
|
+
const Accent = createContext('text-teal-700')
|
|
203
|
+
|
|
204
|
+
const columns = [
|
|
205
|
+
{ key: 'name', header: 'Item', width: '1fr' },
|
|
206
|
+
{
|
|
207
|
+
key: 'cents',
|
|
208
|
+
header: 'Amount',
|
|
209
|
+
width: '30mm',
|
|
210
|
+
align: 'right',
|
|
211
|
+
sum: true,
|
|
212
|
+
format: { minorUnits: 2, decimal: ',', group: '.', suffix: ' €' },
|
|
213
|
+
},
|
|
214
|
+
] satisfies TableColumn<Item>[]
|
|
215
|
+
|
|
216
|
+
function Invoice({ invoice }: { invoice: Promise<InvoiceData> }) {
|
|
217
|
+
const data = use(invoice) // renderToPdf waits for the data
|
|
218
|
+
const accent = useContext(Accent)
|
|
219
|
+
return (
|
|
220
|
+
<Document title={`Invoice ${data.number}`} lang="en">
|
|
221
|
+
<Page
|
|
222
|
+
size="A4"
|
|
223
|
+
className="p-page text-sm"
|
|
224
|
+
footer={
|
|
225
|
+
<Text className="text-right text-xs">
|
|
226
|
+
Page <PageNumber /> of <TotalPages />
|
|
227
|
+
</Text>
|
|
228
|
+
}
|
|
229
|
+
>
|
|
230
|
+
<Text role="h1" className={`mb-6 text-2xl ${accent}`}>
|
|
231
|
+
Invoice {data.number}
|
|
232
|
+
</Text>
|
|
233
|
+
<Table
|
|
234
|
+
data={data.items}
|
|
235
|
+
columns={columns}
|
|
236
|
+
cellClassName="px-2 py-1"
|
|
237
|
+
headerClassName="border-b font-bold"
|
|
238
|
+
totals={{ label: 'Total', className: 'font-bold' }}
|
|
239
|
+
/>
|
|
240
|
+
</Page>
|
|
241
|
+
</Document>
|
|
242
|
+
)
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// In a route handler or server function:
|
|
246
|
+
export async function invoiceResponse(id: string): Promise<Response> {
|
|
247
|
+
const pdf = await renderToPdf(<Invoice invoice={loadInvoice(id)} />, {
|
|
248
|
+
engine,
|
|
249
|
+
timeoutMs: 10_000,
|
|
250
|
+
})
|
|
251
|
+
return new Response(pdf, {
|
|
252
|
+
headers: { 'content-type': 'application/pdf' },
|
|
253
|
+
})
|
|
254
|
+
}
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
- Keep the project's JSX setup; `react` and `react-dom` 19 are optional peer dependencies.
|
|
258
|
+
- Load data with `use()` (inside or outside `<Suspense>`), not with `async` components. Every error React reports fails the render, also inside `<Suspense>`, with React's `componentStack`. `timeoutMs` and `signal` abort a render that takes too long (`ABORTED`), React and the engine alike.
|
|
259
|
+
- `renderToPdfDetailed()` returns page count, warnings and wrap diagnostics like `engine.renderDetailed()`. Without `engine`, the default engine of `render()` is used.
|
|
260
|
+
- Run servers with `NODE_ENV=production`: React's development build is about five times slower on element-heavy documents.
|
|
261
|
+
- Effects never run and state keeps its initial value: a document is rendered once.
|
|
262
|
+
|
|
263
|
+
### Factories
|
|
264
|
+
|
|
265
|
+
<!-- snippet: web/src/tests/docs/usage/factories.tsx#factories -->
|
|
266
|
+
|
|
267
|
+
```tsx
|
|
268
|
+
import {
|
|
269
|
+
document,
|
|
270
|
+
page,
|
|
271
|
+
pageNumber,
|
|
272
|
+
render,
|
|
273
|
+
table,
|
|
274
|
+
text,
|
|
275
|
+
totalPages,
|
|
276
|
+
view,
|
|
277
|
+
} from '@rentnerkev/pdf'
|
|
278
|
+
|
|
279
|
+
const report = document({ title: 'Report', lang: 'en' }, [
|
|
280
|
+
page(
|
|
281
|
+
{
|
|
282
|
+
size: 'A4',
|
|
283
|
+
className: 'p-page',
|
|
284
|
+
footer: text({ className: 'text-xs text-right' }, [
|
|
285
|
+
'Page ',
|
|
286
|
+
pageNumber(),
|
|
287
|
+
' of ',
|
|
288
|
+
totalPages(),
|
|
289
|
+
]),
|
|
290
|
+
},
|
|
291
|
+
[
|
|
292
|
+
text({ role: 'h1', className: 'text-2xl font-bold' }, 'Report'),
|
|
293
|
+
view({ className: 'mt-4 flex gap-4' }, [
|
|
294
|
+
text({ className: 'flex-1' }, 'Left column'),
|
|
295
|
+
text({ className: 'flex-1' }, 'Right column'),
|
|
296
|
+
]),
|
|
297
|
+
table({
|
|
298
|
+
data: [{ month: 'January', cents: 125_000 }],
|
|
299
|
+
columns: [
|
|
300
|
+
{ key: 'month', header: 'Month', width: '1fr' },
|
|
301
|
+
{
|
|
302
|
+
key: 'cents',
|
|
303
|
+
header: 'Revenue',
|
|
304
|
+
format: { minorUnits: 2 },
|
|
305
|
+
},
|
|
306
|
+
],
|
|
307
|
+
}),
|
|
308
|
+
],
|
|
309
|
+
),
|
|
310
|
+
])
|
|
311
|
+
|
|
312
|
+
const pdf = await render(report)
|
|
313
|
+
```
|
|
314
|
+
|
|
315
|
+
`renderToIr()` turns JSX into the same data, for logging and snapshot tests:
|
|
316
|
+
|
|
317
|
+
<!-- snippet: web/src/tests/docs/usage/factories.tsx#ir -->
|
|
318
|
+
|
|
319
|
+
```tsx
|
|
320
|
+
/** @jsxImportSource @rentnerkev/pdf */
|
|
321
|
+
import { Document, Page, renderToIr, Text } from '@rentnerkev/pdf'
|
|
322
|
+
|
|
323
|
+
const ir = await renderToIr(
|
|
324
|
+
<Document title="Snapshot">
|
|
325
|
+
<Page>
|
|
326
|
+
<Text>Hello</Text>
|
|
327
|
+
</Page>
|
|
328
|
+
</Document>,
|
|
329
|
+
)
|
|
330
|
+
// ir.pages[0].children[0] is { t: 'text', text: 'Hello' }
|
|
331
|
+
```
|
|
332
|
+
|
|
333
|
+
## Engine
|
|
334
|
+
|
|
335
|
+
<!-- snippet: web/src/tests/docs/usage/engine.tsx#create -->
|
|
336
|
+
|
|
337
|
+
```tsx
|
|
338
|
+
import { readFile } from 'node:fs/promises'
|
|
339
|
+
import { createEngine } from '@rentnerkev/pdf'
|
|
340
|
+
|
|
341
|
+
// Create the engine once (at startup) and reuse it for every render: it
|
|
342
|
+
// keeps fonts, parsed classes and decoded images between renders.
|
|
343
|
+
export const engine = await createEngine({
|
|
344
|
+
fonts: [
|
|
345
|
+
await readFile('fonts/Brand-Regular.ttf'),
|
|
346
|
+
await readFile('fonts/Brand-Bold.ttf'),
|
|
347
|
+
],
|
|
348
|
+
theme: { '--color-brand': '#0f766e' },
|
|
349
|
+
strict: process.env.NODE_ENV === 'development',
|
|
350
|
+
})
|
|
351
|
+
```
|
|
352
|
+
|
|
353
|
+
| Option | Default | Meaning |
|
|
354
|
+
| --------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
355
|
+
| `fonts` | `[]` | TrueType/OpenType files as bytes (`Uint8Array` or `ArrayBuffer`). The first font's family is the default; every font is a fallback for missing characters; [`registerFont()`](#fonts-later-and-closing) adds more |
|
|
356
|
+
| `defaultFont` | `true` | Registers the bundled Noto Sans (Regular, Bold, Italic, Bold Italic; Latin, Greek, Cyrillic) |
|
|
357
|
+
| `theme` | – | App design tokens: `themeFromCss()`/`themeFromCssFile()` results, `{ '--token': value }` overrides, or a list ([themes](#themes)) |
|
|
358
|
+
| `rootFontSize` | `16` | CSS pixels per `rem`: `p-4` = 1 rem = 12 pt |
|
|
359
|
+
| `strict` | `false` | Class and value warnings become `UNSUPPORTED_CLASS` errors ([strict mode](#strict-mode)) |
|
|
360
|
+
| `cache.imageBytesMax` | 64 MiB | Cache of decoded images, SVGs and letterhead PDFs, found by content; `0` disables it |
|
|
361
|
+
| `cache.shapedRunsMax` | 16,384 | Cache of shaped text runs (labels, cells, short lines) from their second occurrence; `0` disables it |
|
|
362
|
+
| `threads` | `'auto'` | Native: documents rendering at once and the pool that shapes a document's paragraphs; one per core. WebAssembly has one |
|
|
363
|
+
| `limits` | – | Overrides of the [limits](#limits) for untrusted input, or `'unlimited'` for trusted batch jobs |
|
|
364
|
+
| `backend` | `'auto'` | `'native'`, `'wasm'`, or `'auto'`: native where the addon loads, else WebAssembly with a one-time console hint |
|
|
365
|
+
| `wasmModule` | – | The `.wasm` module (bytes, URL or `WebAssembly.Module`) for runtimes that cannot read it next to the package, such as Workers |
|
|
366
|
+
|
|
367
|
+
Caches and threads never change the output: every thread count and cache state renders the same bytes.
|
|
368
|
+
|
|
369
|
+
<!-- snippet: web/src/tests/docs/usage/engine.tsx#options -->
|
|
370
|
+
|
|
371
|
+
```tsx
|
|
372
|
+
// A service that renders documents from untrusted input: four threads,
|
|
373
|
+
// tighter limits and a larger cache of shaped text.
|
|
374
|
+
export const service = await createEngine({
|
|
375
|
+
threads: 4,
|
|
376
|
+
cache: { shapedRunsMax: 50_000 },
|
|
377
|
+
limits: { maxPages: 500, maxImagePixels: 25_000_000 },
|
|
378
|
+
})
|
|
379
|
+
|
|
380
|
+
// Trusted batch jobs can lift every limit.
|
|
381
|
+
export const batchJobs = await createEngine({ limits: 'unlimited' })
|
|
382
|
+
```
|
|
383
|
+
|
|
384
|
+
Render methods take a JSX element or a factory document:
|
|
385
|
+
|
|
386
|
+
<!-- snippet: web/src/tests/docs/usage/engine.tsx#render -->
|
|
387
|
+
|
|
388
|
+
```tsx
|
|
389
|
+
import { Document, Page, Text } from '@rentnerkev/pdf'
|
|
390
|
+
|
|
391
|
+
const letter = (
|
|
392
|
+
<Document title="Letter">
|
|
393
|
+
<Page size="A4" className="p-page">
|
|
394
|
+
<Text className="text-brand">Dear Ms Musterfrau,</Text>
|
|
395
|
+
</Page>
|
|
396
|
+
</Document>
|
|
397
|
+
)
|
|
398
|
+
|
|
399
|
+
// Off the event loop on the native backend.
|
|
400
|
+
const pdf: Uint8Array = await engine.render(letter)
|
|
401
|
+
|
|
402
|
+
// Page count, warnings and wrap diagnostics as well.
|
|
403
|
+
const { pageCount, warnings, diagnostics } = await engine.renderDetailed(letter)
|
|
404
|
+
|
|
405
|
+
// On the calling thread; components must be synchronous.
|
|
406
|
+
const sameBytes: Uint8Array = engine.renderSync(letter)
|
|
407
|
+
```
|
|
408
|
+
|
|
409
|
+
`render(element)` from the main package creates a default engine (bundled fonts, default options) on first use and reuses it; use your own engine for fonts, themes or `strict`.
|
|
410
|
+
|
|
411
|
+
**Backends.** Both render the same input to the same bytes. The native engine renders on its own threads, off the event loop: at most `threads` documents at once, further renders wait in order (`engine.stats().rendersQueued`). The WebAssembly engine renders on the calling thread: `render()` returns a promise but blocks the thread while it works. If its module crashes, the call rejects with `INTERNAL` (a bug in RentnerPDF) and the engine starts the module again for the next call; it registers the same font buffers again, so leave them unchanged.
|
|
412
|
+
|
|
413
|
+
<!-- snippet: web/src/tests/docs/usage/engine.tsx#backend -->
|
|
414
|
+
|
|
415
|
+
```tsx
|
|
416
|
+
const wasm = await createEngine({ backend: 'wasm' })
|
|
417
|
+
const backend = wasm.backend // 'wasm'; 'auto' gives 'native' where the addon loads
|
|
418
|
+
const version = wasm.version // the engine's version, the same as the package's
|
|
419
|
+
```
|
|
420
|
+
|
|
421
|
+
`engine.version` is the version of the engine that renders: the native addon's or the WebAssembly build's, the same as the package version when all `@rentnerkev/pdf*` packages match.
|
|
422
|
+
|
|
423
|
+
### Cancellation
|
|
424
|
+
|
|
425
|
+
Every render takes a `signal`. An aborted signal rejects the render with `ABORTED` (the signal's reason as `cause`) at once; the native engine stops working on the document at its next page or paragraph, and a render still waiting for a thread never starts. A WebAssembly render blocks its thread, so only a signal that aborted before it started stops it.
|
|
426
|
+
|
|
427
|
+
<!-- snippet: web/src/tests/docs/usage/engine.tsx#cancel -->
|
|
428
|
+
|
|
429
|
+
```tsx
|
|
430
|
+
import { RentnerPdfError } from '@rentnerkev/pdf'
|
|
431
|
+
|
|
432
|
+
// The client went away: the render rejects with ABORTED at once, and the
|
|
433
|
+
// native engine stops at its next page or paragraph.
|
|
434
|
+
const controller = new AbortController()
|
|
435
|
+
const rendering = engine.render(letter, { signal: controller.signal })
|
|
436
|
+
controller.abort()
|
|
437
|
+
let cancelled = ''
|
|
438
|
+
try {
|
|
439
|
+
await rendering
|
|
440
|
+
} catch (error) {
|
|
441
|
+
if (error instanceof RentnerPdfError) cancelled = error.code // 'ABORTED'
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
// A time limit for one render.
|
|
445
|
+
const inTime = await engine.render(letter, {
|
|
446
|
+
signal: AbortSignal.timeout(10_000),
|
|
447
|
+
})
|
|
448
|
+
```
|
|
449
|
+
|
|
450
|
+
### Many documents
|
|
451
|
+
|
|
452
|
+
`renderMany()` takes an array, a generator or an async iterable (a database cursor) of documents and yields each document's result in input order: `{ ok: true, index, pdf, pageCount, warnings, diagnostics }` or `{ ok: false, index, error }`. It reads the next document only when one of `concurrency` slots is free (default: twice the engine's threads; one on WebAssembly), so neither the input nor the results pile up, and limits apply to each document on its own. `stopOnError: true` ends the batch at the first failure instead; `signal` and breaking out of the loop cancel the documents in progress.
|
|
453
|
+
|
|
454
|
+
<!-- snippet: web/src/tests/docs/usage/engine.tsx#many -->
|
|
455
|
+
|
|
456
|
+
```tsx
|
|
457
|
+
const names = ['Ms Musterfrau', 'Mr Mustermann', 'Dr Beispiel']
|
|
458
|
+
|
|
459
|
+
// Results arrive in input order as they are ready. The next document is
|
|
460
|
+
// read only when a slot is free, so a generator of 100,000 letters needs
|
|
461
|
+
// the memory of a few; a failed document does not end the batch.
|
|
462
|
+
let batchPages = 0
|
|
463
|
+
for await (const result of engine.renderMany(
|
|
464
|
+
names.map((name) => (
|
|
465
|
+
<Document title="Letter">
|
|
466
|
+
<Page size="A4" className="p-page">
|
|
467
|
+
<Text>Dear {name},</Text>
|
|
468
|
+
</Page>
|
|
469
|
+
</Document>
|
|
470
|
+
)),
|
|
471
|
+
)) {
|
|
472
|
+
if (result.ok)
|
|
473
|
+
batchPages += result.pageCount // and store result.pdf
|
|
474
|
+
else console.error(`letter ${result.index} failed`, result.error)
|
|
475
|
+
}
|
|
476
|
+
```
|
|
477
|
+
|
|
478
|
+
### Streams
|
|
479
|
+
|
|
480
|
+
**Experimental:** exempt from SemVer in 1.x until promoted; the chunks stay, but when they arrive may change.
|
|
481
|
+
|
|
482
|
+
`renderToStream()` returns the PDF as a `ReadableStream` of 64 KiB chunks; cancelling the stream cancels the render. The engine writes the whole document before the first chunk, because the PDF writer (krilla) keeps the document until it is finished; writing pages into the stream while they are rendered is planned after 1.0.
|
|
483
|
+
|
|
484
|
+
<!-- snippet: web/src/tests/docs/usage/engine.tsx#stream -->
|
|
485
|
+
|
|
486
|
+
```tsx
|
|
487
|
+
// The PDF as a stream of chunks, for example as a response body.
|
|
488
|
+
export const download = (): Response =>
|
|
489
|
+
new Response(engine.renderToStream(letter), {
|
|
490
|
+
headers: { 'content-type': 'application/pdf' },
|
|
491
|
+
})
|
|
492
|
+
```
|
|
493
|
+
|
|
494
|
+
### Fonts later, and closing
|
|
495
|
+
|
|
496
|
+
`engine.registerFont(bytes)` adds a font while the engine runs. A render uses the fonts the engine has when its document reaches the engine (after its components are evaluated): renders already there keep their fonts, later ones use the new font. It works like a font appended to `fonts`, except that the default family never changes: a new family comes last in the fallback chain, a font of a family you registered before adds a face (a bold face, say), and a font of the bundled Noto Sans family replaces it. Invalid fonts reject with `UNSUPPORTED_FONT`, oversized ones with `LIMIT_EXCEEDED`.
|
|
497
|
+
|
|
498
|
+
`engine.close()` releases the engine: its memory, caches and threads, or the WebAssembly instance. From the call on, every method rejects with `ENGINE_CLOSED`; renders still in progress are cancelled and reject with `ABORTED` (native ones stop at their next page or paragraph), and the promise resolves once they have stopped. Engines support `using` and `await using`; the worker engine of `@rentnerkev/pdf/worker` has the same `registerFont()` and `close()`.
|
|
499
|
+
|
|
500
|
+
<!-- snippet: web/src/tests/docs/usage/engine.tsx#lifecycle -->
|
|
501
|
+
|
|
502
|
+
```tsx
|
|
503
|
+
// Fonts can come later, for example a font uploaded by a tenant: renders
|
|
504
|
+
// that reach the engine afterwards use it, renders already running keep
|
|
505
|
+
// their fonts, and documents that do not use it keep their bytes.
|
|
506
|
+
await engine.registerFont(await readFile('fonts/NotoSansHebrew-Regular.ttf'))
|
|
507
|
+
const greeting = await engine.renderDetailed(
|
|
508
|
+
<Document title="Greeting" lang="he">
|
|
509
|
+
<Page size="A4" className="p-page">
|
|
510
|
+
<Text>שלום</Text>
|
|
511
|
+
</Page>
|
|
512
|
+
</Document>,
|
|
513
|
+
)
|
|
514
|
+
|
|
515
|
+
// close() releases the engine (memory, caches, threads, the WebAssembly
|
|
516
|
+
// instance): renders still running reject with ABORTED, later calls with
|
|
517
|
+
// ENGINE_CLOSED. `await using` closes it at the end of the scope.
|
|
518
|
+
let closedCode = ''
|
|
519
|
+
{
|
|
520
|
+
await using scoped = await createEngine()
|
|
521
|
+
await scoped.render(letter)
|
|
522
|
+
await scoped.close()
|
|
523
|
+
try {
|
|
524
|
+
await scoped.render(letter)
|
|
525
|
+
} catch (error) {
|
|
526
|
+
if (error instanceof RentnerPdfError) closedCode = error.code // 'ENGINE_CLOSED'
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
```
|
|
530
|
+
|
|
531
|
+
## Components
|
|
532
|
+
|
|
533
|
+
The same components exist in `@rentnerkev/pdf` (own runtime) and `@rentnerkev/pdf/react`. `Page`, `View`, `Text`, `Image`, `Svg`, `Table`, `Row`, `Cell`, `Link` and `Keep` take `className` and `style`.
|
|
534
|
+
|
|
535
|
+
| Component | Props (besides `className`, `style`) | Children |
|
|
536
|
+
| ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------ |
|
|
537
|
+
| `Document` | `title`, `author`, `subject`, `keywords`, `lang`, `dir`, `creator`, `creationDate`, `standard`, `tagged`, `attachments`, `facturX` | `Page`s |
|
|
538
|
+
| `Page` | `size` (`'A3'`, `'A4'`, `'A5'`, `'Letter'`, `'Legal'`, `{ width, height }` in pt), `orientation`, `header`, `footer`, `first`, `odd`, `even`, `last`, `numbering`, `letterhead` | content |
|
|
539
|
+
| `View` | `id`, `bookmark`, `marker`, `role`, `alt`, `lang`, `dir` | content |
|
|
540
|
+
| `Text` | `id`, `bookmark`, `marker`, `role` (`'h1'` … `'h6'` become bookmarks), `lang`, `dir`, `alt` | strings, numbers, `PageNumber`, `TotalPages`, `Marker` |
|
|
541
|
+
| `Image` | `src` (bytes), `alt`, `role`, `id`, `bookmark` | – |
|
|
542
|
+
| `Svg` | `src` (markup or bytes), `alt`, `role`, `id`, `bookmark` | – |
|
|
543
|
+
| `Table`, `Row`, `Cell` | see [Tables](#tables) | `Row`s, `Cell`s, content |
|
|
544
|
+
| `Link` | `href` (`#id`, `https:`, `http:`, `mailto:`, `tel:`) and the `View` props | content |
|
|
545
|
+
| `Anchor` | `id`, `bookmark` | – |
|
|
546
|
+
| `PageBreak` | – | – |
|
|
547
|
+
| `Keep` | `withNext` and the `View` props | content |
|
|
548
|
+
| `PageNumber`, `TotalPages`, `Marker` | `format`; `scope` (`'document'`, `'section'`); `name`, `select` | – |
|
|
549
|
+
|
|
550
|
+
"Content" is `View`, `Text`, `Image`, `Svg`, `Table`, `Link`, `Anchor`, `PageBreak` and `Keep`. Text belongs inside `Text` (or a `Cell`); white space between boxes is ignored. Nested elements inside `Text` (inline bold, inline links) are not supported yet.
|
|
551
|
+
|
|
552
|
+
`@rentnerkev/pdf` and `@rentnerkev/pdf/react` export the types used by the props, including `Style`, `StyleLength`, `PageSize`, `Orientation`, `PageNumbering`, `PageNumberFormat`, `NumberFormat`, `RunningTotals`, `TableTotals`, `Standard`, `FacturX`, `Relationship`, `Dir` and `TextAlign`. The main entry exports the factories' input types (`DocumentInput`, `PageInput`, `NodeInput`, …) and the generated document and node types under `ir`. Input lists are readonly, so a `readonly NodeInput[]` can be passed as `children`. The package writes the columnar wire fields internally (`Document.channel`, `TableNode.rows`, `TableColumn.text` and `TableColumn.values`).
|
|
553
|
+
|
|
554
|
+
### Document and Page
|
|
555
|
+
|
|
556
|
+
<!-- snippet: web/src/tests/docs/usage/components.tsx#document -->
|
|
557
|
+
|
|
558
|
+
```tsx
|
|
559
|
+
const pdf = await render(
|
|
560
|
+
<Document
|
|
561
|
+
title="Invoice 2026-001"
|
|
562
|
+
author="Muster GmbH"
|
|
563
|
+
subject="Invoice"
|
|
564
|
+
keywords={['invoice', '2026']}
|
|
565
|
+
lang="de-DE"
|
|
566
|
+
creator="Billing 4.2"
|
|
567
|
+
creationDate="2026-12-01"
|
|
568
|
+
>
|
|
569
|
+
{pages}
|
|
570
|
+
<Page size="A4" className="p-page">
|
|
571
|
+
{layout}
|
|
572
|
+
{flow}
|
|
573
|
+
</Page>
|
|
574
|
+
</Document>,
|
|
575
|
+
)
|
|
576
|
+
```
|
|
577
|
+
|
|
578
|
+
Without `creationDate` the PDF has no date, so the same input always gives the same bytes. The producer is always `RentnerPDF <version>`.
|
|
579
|
+
|
|
580
|
+
<!-- snippet: web/src/tests/docs/usage/components.tsx#page -->
|
|
581
|
+
|
|
582
|
+
```tsx
|
|
583
|
+
const pages = (
|
|
584
|
+
<>
|
|
585
|
+
<Page size="A4" className="p-page">
|
|
586
|
+
<Text>A4 portrait with 20 mm padding (the p-page token)</Text>
|
|
587
|
+
</Page>
|
|
588
|
+
<Page size="A5" orientation="landscape" className="px-[15mm] py-[10mm]">
|
|
589
|
+
<Text>A5 landscape</Text>
|
|
590
|
+
</Page>
|
|
591
|
+
<Page size={{ width: 283.46, height: 425.2 }} className="p-4">
|
|
592
|
+
<Text>100 × 150 mm label (sizes in points)</Text>
|
|
593
|
+
</Page>
|
|
594
|
+
</>
|
|
595
|
+
)
|
|
596
|
+
```
|
|
597
|
+
|
|
598
|
+
A `Page` is a template: its content flows onto as many pages as it needs. Page padding is the margin; `header` and `footer` sit inside it ([templates](#page-templates-and-placeholders)).
|
|
599
|
+
|
|
600
|
+
### View and Text
|
|
601
|
+
|
|
602
|
+
`View` is a block box; `flex` and `grid` classes make it a flex or grid container (CSS defaults: `flex` lays out in a row).
|
|
603
|
+
|
|
604
|
+
<!-- snippet: web/src/tests/docs/usage/components.tsx#view-text -->
|
|
605
|
+
|
|
606
|
+
```tsx
|
|
607
|
+
const layout = (
|
|
608
|
+
<View className="grid grid-cols-[1fr_40mm] gap-4">
|
|
609
|
+
<View className="flex flex-col gap-1">
|
|
610
|
+
<Text role="h2" className="text-lg font-semibold">
|
|
611
|
+
Muster GmbH
|
|
612
|
+
</Text>
|
|
613
|
+
<Text>Musterstraße 1, 12345 Musterstadt</Text>
|
|
614
|
+
</View>
|
|
615
|
+
<Text className="text-right">
|
|
616
|
+
{3} items, due in {14} days
|
|
617
|
+
</Text>
|
|
618
|
+
</View>
|
|
619
|
+
)
|
|
620
|
+
```
|
|
621
|
+
|
|
622
|
+
### Page flow
|
|
623
|
+
|
|
624
|
+
<!-- snippet: web/src/tests/docs/usage/components.tsx#flow -->
|
|
625
|
+
|
|
626
|
+
```tsx
|
|
627
|
+
const flow = (
|
|
628
|
+
<>
|
|
629
|
+
<Keep withNext>
|
|
630
|
+
<Text role="h2" className="text-lg font-bold">
|
|
631
|
+
Terms
|
|
632
|
+
</Text>
|
|
633
|
+
</Keep>
|
|
634
|
+
<Text className="widows-3 orphans-3">Long paragraph …</Text>
|
|
635
|
+
<Keep className="mt-4">
|
|
636
|
+
<Text>This block moves to the next page as a whole …</Text>
|
|
637
|
+
<Text>… if it does not fit on this one.</Text>
|
|
638
|
+
</Keep>
|
|
639
|
+
<PageBreak />
|
|
640
|
+
<Text>Appendix A starts on a new page.</Text>
|
|
641
|
+
<Text className="break-before-page">So does appendix B.</Text>
|
|
642
|
+
</>
|
|
643
|
+
)
|
|
644
|
+
```
|
|
645
|
+
|
|
646
|
+
| Want | Use |
|
|
647
|
+
| ------------------------------------ | ----------------------------------------------------------- |
|
|
648
|
+
| Start the next content on a new page | `<PageBreak />`, `break-before-page`, `break-after-page` |
|
|
649
|
+
| Keep a block on one page | `<Keep>`, `break-inside-avoid` |
|
|
650
|
+
| Keep a heading with what follows | `<Keep withNext>`, `keep-with-next` (= `break-after-avoid`) |
|
|
651
|
+
| Control lines at page breaks | `widows-*`, `orphans-*` (default 2) |
|
|
652
|
+
|
|
653
|
+
A kept block that is taller than a page is split anyway; `renderDetailed()` reports it ([diagnostics](#wrap-diagnostics)).
|
|
654
|
+
|
|
655
|
+
## Styling
|
|
656
|
+
|
|
657
|
+
### className
|
|
658
|
+
|
|
659
|
+
`className` follows Tailwind CSS v4: the same names, units like the browser (`px` = 0.75 pt, `rem` = 12 pt), print units everywhere (`w-[42mm]`, `text-[10pt]`), arbitrary values, `/opacity` modifiers, important (`p-4!`) and "last class wins" per property, like `tailwind-merge`. No Tailwind build step runs; the engine parses the classes. `clsx`, `cn()` and `twMerge()` return strings, so they work unchanged:
|
|
660
|
+
|
|
661
|
+
<!-- snippet: web/src/tests/docs/usage/styling.tsx#classname -->
|
|
662
|
+
|
|
663
|
+
```tsx
|
|
664
|
+
import { clsx } from 'clsx'
|
|
665
|
+
import { Document, Page, Text, View } from '@rentnerkev/pdf'
|
|
666
|
+
|
|
667
|
+
function Badge({ overdue }: { overdue: boolean }) {
|
|
668
|
+
return (
|
|
669
|
+
<Text
|
|
670
|
+
className={clsx(
|
|
671
|
+
'rounded px-2 py-0.5 text-xs font-semibold',
|
|
672
|
+
overdue
|
|
673
|
+
? 'bg-red-100 text-red-700'
|
|
674
|
+
: 'bg-teal-50 text-teal-700',
|
|
675
|
+
)}
|
|
676
|
+
>
|
|
677
|
+
{overdue ? 'Overdue' : 'Open'}
|
|
678
|
+
</Text>
|
|
679
|
+
)
|
|
680
|
+
}
|
|
681
|
+
```
|
|
682
|
+
|
|
683
|
+
The [support matrix](tailwind-support.md) lists every utility with what it does on paper: rendered, parsed with rendering planned (for example `rounded`, `opacity-*`, `underline`), unsupported with advice, or without effect.
|
|
684
|
+
|
|
685
|
+
Variants with a meaning on paper are active: `first:`, `last:`, `only:`, `odd:`, `even:`, `ltr:`, `rtl:` and `print:` (always). Interactive, dark-mode and responsive variants (`hover:`, `dark:`, `md:`, …) never match and produce an `IGNORED_VARIANT` warning, so components shared with the web app still render.
|
|
686
|
+
|
|
687
|
+
<!-- snippet: web/src/tests/docs/usage/styling.tsx#variants -->
|
|
688
|
+
|
|
689
|
+
```tsx
|
|
690
|
+
const rows = ['Consulting', 'Travel', 'Hosting'].map((name) => (
|
|
691
|
+
<Text key={name} className="px-2 py-1 odd:bg-gray-50 last:border-b">
|
|
692
|
+
{name}
|
|
693
|
+
</Text>
|
|
694
|
+
))
|
|
695
|
+
```
|
|
696
|
+
|
|
697
|
+
### style
|
|
698
|
+
|
|
699
|
+
Typed camelCase properties win over `className`, like inline styles. Numbers are points; strings are CSS values (`'5mm'`, `'1rem'`, `'calc(100% - 20mm)'`, `var(--token)`, `oklch(…)`).
|
|
700
|
+
|
|
701
|
+
<!-- snippet: web/src/tests/docs/usage/styling.tsx#style -->
|
|
702
|
+
|
|
703
|
+
```tsx
|
|
704
|
+
const box = (
|
|
705
|
+
<View
|
|
706
|
+
className="border border-gray-300 p-4"
|
|
707
|
+
style={{
|
|
708
|
+
paddingTop: 24,
|
|
709
|
+
width: '80mm',
|
|
710
|
+
backgroundColor: 'oklch(97% 0.01 180)',
|
|
711
|
+
}}
|
|
712
|
+
>
|
|
713
|
+
<Text style={{ fontSize: 9, lineHeight: 1.4 }}>
|
|
714
|
+
Numbers are points.
|
|
715
|
+
</Text>
|
|
716
|
+
</View>
|
|
717
|
+
)
|
|
718
|
+
```
|
|
719
|
+
|
|
720
|
+
### Themes
|
|
721
|
+
|
|
722
|
+
The engine starts from Tailwind's default theme plus RentnerPDF's paper tokens (`bg-paper`, `text-ink`, `p-page`). Add the app's tokens from CSS, JS overrides, or both:
|
|
723
|
+
|
|
724
|
+
<!-- snippet: web/src/tests/docs/usage/styling.tsx#theme -->
|
|
725
|
+
|
|
726
|
+
```tsx
|
|
727
|
+
import { createEngine, themeFromCss } from '@rentnerkev/pdf'
|
|
728
|
+
|
|
729
|
+
const engine = await createEngine({
|
|
730
|
+
theme: [
|
|
731
|
+
themeFromCss(`
|
|
732
|
+
@theme { --color-brand: #0f766e; --font-display: 'Noto Sans'; }
|
|
733
|
+
.rentner-pdf { --color-brand: #115e59; }
|
|
734
|
+
`),
|
|
735
|
+
{ '--spacing-page': '25mm' }, // JS overrides, applied last
|
|
736
|
+
],
|
|
737
|
+
rootFontSize: 16,
|
|
738
|
+
})
|
|
739
|
+
const themeWarnings = engine.themeWarnings // INVALID_THEME warnings; [] when sound
|
|
740
|
+
```
|
|
741
|
+
|
|
742
|
+
In Node.js and Bun, read the app's Tailwind entry CSS directly:
|
|
743
|
+
|
|
744
|
+
<!-- snippet: web/src/tests/docs/usage/styling.tsx#theme-file -->
|
|
745
|
+
|
|
746
|
+
```tsx
|
|
747
|
+
import { themeFromCssFile } from '@rentnerkev/pdf/node'
|
|
748
|
+
|
|
749
|
+
const appEngine = await createEngine({
|
|
750
|
+
// Follows relative and @rentnerkev/* imports; tailwindcss is built in.
|
|
751
|
+
theme: await themeFromCssFile('src/styles.css'),
|
|
752
|
+
})
|
|
753
|
+
```
|
|
754
|
+
|
|
755
|
+
- The reader takes `@theme` blocks, custom properties on `:root` and on `.rentner-pdf` (`scopes` option), and `@media print`; it never runs Tailwind. Keep dark web values on `:root` and paper values in `.rentner-pdf`; the shared `--rentner-*` tokens default to paper colors.
|
|
756
|
+
- Override order: Tailwind default → `@rentnerkev/pdf/tailwind.css` → app CSS (`@theme`, `:root`, scopes) → JS overrides.
|
|
757
|
+
- `themeFromCss(css)` works in any runtime; `themeFromCssFile()` (`@rentnerkev/pdf/node`) follows relative imports and `@rentnerkev/*` packages. `rootFontSize` changes what `1rem` is.
|
|
758
|
+
- Broken CSS never throws: problems are `INVALID_THEME` warnings in `engine.themeWarnings`.
|
|
759
|
+
|
|
760
|
+
### Editor support
|
|
761
|
+
|
|
762
|
+
Install [Tailwind CSS IntelliSense](https://marketplace.visualstudio.com/items?itemName=bradlc.vscode-tailwindcss) and:
|
|
763
|
+
|
|
764
|
+
- in a React/Tailwind project, add one line after `@import 'tailwindcss';` in the CSS entry: `@import '@rentnerkev/pdf/tailwind.css';`
|
|
765
|
+
- in a Bun or Node.js service without a frontend, run `bun add -d tailwindcss` and create an editor-only `pdf.css` with both imports and your `@theme` tokens (`themeFromCssFile('pdf.css')` reuses it);
|
|
766
|
+
- for `cn()`, `clsx()` and the table props, add to `.vscode/settings.json`:
|
|
767
|
+
|
|
768
|
+
```json
|
|
769
|
+
{
|
|
770
|
+
"tailwindCSS.classFunctions": ["cn", "clsx", "twMerge"],
|
|
771
|
+
"tailwindCSS.classAttributes": [
|
|
772
|
+
"class",
|
|
773
|
+
"className",
|
|
774
|
+
"rowClassName",
|
|
775
|
+
"headerClassName",
|
|
776
|
+
"cellClassName"
|
|
777
|
+
],
|
|
778
|
+
"tailwindCSS.experimental.classRegex": ["[cC]lassName:\\s*['\"]([^'\"]*)"]
|
|
779
|
+
}
|
|
780
|
+
```
|
|
781
|
+
|
|
782
|
+
The `classRegex` line covers `className` keys in data-table `columns`, `totals` and `runningTotals`, as well as in factory props. Completions and hovers then include the print utilities (`keep-with-next`, `widows-2`, `repeat-header`) and the tokens `bg-paper`, `text-ink` and `p-page`. The language server needs a few seconds after the editor starts before the first suggestions appear.
|
|
783
|
+
|
|
784
|
+
`cn()` works unchanged. To let `twMerge` dedupe the print utilities too:
|
|
785
|
+
|
|
786
|
+
<!-- snippet: web/src/tests/docs/usage/styling.tsx#tailwind-merge -->
|
|
787
|
+
|
|
788
|
+
```tsx
|
|
789
|
+
import { extendTailwindMerge } from 'tailwind-merge'
|
|
790
|
+
import {
|
|
791
|
+
rentnerPdfMergeConfig,
|
|
792
|
+
type RentnerPdfClassGroupId,
|
|
793
|
+
} from '@rentnerkev/pdf/tailwind-merge'
|
|
794
|
+
|
|
795
|
+
// twMerge that also knows the print utilities: 'widows-2 widows-3' → 'widows-3'
|
|
796
|
+
export const twMerge = extendTailwindMerge<RentnerPdfClassGroupId>(
|
|
797
|
+
rentnerPdfMergeConfig,
|
|
798
|
+
)
|
|
799
|
+
```
|
|
800
|
+
|
|
801
|
+
## Tables
|
|
802
|
+
|
|
803
|
+
### Element tables
|
|
804
|
+
|
|
805
|
+
`Table` holds `Row`s, a `Row` holds `Cell`s. Header rows come first and repeat on every page; footer rows come last and repeat too (`repeatHeader`, `repeatFooter`).
|
|
806
|
+
|
|
807
|
+
<!-- snippet: web/src/tests/docs/usage/tables.tsx#element-table -->
|
|
808
|
+
|
|
809
|
+
```tsx
|
|
810
|
+
import { Cell, Row, Table } from '@rentnerkev/pdf'
|
|
811
|
+
|
|
812
|
+
const euro = { minorUnits: 2, decimal: ',', group: '.', suffix: ' €' }
|
|
813
|
+
|
|
814
|
+
const items = (
|
|
815
|
+
<Table
|
|
816
|
+
columns={[
|
|
817
|
+
{ width: '1fr' },
|
|
818
|
+
{ width: '20mm', align: 'right' },
|
|
819
|
+
{ width: '30mm', align: 'right', sum: true, format: euro },
|
|
820
|
+
]}
|
|
821
|
+
cellClassName="px-2 py-1"
|
|
822
|
+
className="text-sm"
|
|
823
|
+
>
|
|
824
|
+
<Row header className="border-b font-bold">
|
|
825
|
+
<Cell>Item</Cell>
|
|
826
|
+
<Cell>Qty</Cell>
|
|
827
|
+
<Cell>Amount</Cell>
|
|
828
|
+
</Row>
|
|
829
|
+
<Row className="odd:bg-gray-50">
|
|
830
|
+
<Cell>Consulting</Cell>
|
|
831
|
+
<Cell>8</Cell>
|
|
832
|
+
<Cell value={120_000} />
|
|
833
|
+
</Row>
|
|
834
|
+
<Row className="odd:bg-gray-50">
|
|
835
|
+
<Cell colSpan={2}>Travel expenses (flat rate)</Cell>
|
|
836
|
+
<Cell value={14_550} />
|
|
837
|
+
</Row>
|
|
838
|
+
<Row footer className="border-t font-bold">
|
|
839
|
+
<Cell colSpan={2}>Total</Cell>
|
|
840
|
+
<Cell value={134_550} />
|
|
841
|
+
</Row>
|
|
842
|
+
</Table>
|
|
843
|
+
)
|
|
844
|
+
```
|
|
845
|
+
|
|
846
|
+
- `columns[i]`: `width` (points, `'auto'` (default), `'1fr'`, `'30mm'`, `'25%'`, `'min-content'`, `'max-content'`), `align`, and for number columns `sum` and `format`.
|
|
847
|
+
- `<Cell value={cents} />` shows an integer in minor units with the column's `format` (`{ minorUnits, decimal, group, prefix, suffix }`); keep money in cents, never floats.
|
|
848
|
+
- `cellClassName` applies to every cell first. `colSpan` and `rowSpan` span cells; `align-top`/`align-middle`/`align-bottom` place cell content. Rows never split; a table breaks between rows and starts on the next page when its header and first row do not fit.
|
|
849
|
+
- `odd:`/`even:` count rows within their section, so `odd:bg-gray-50` stripes the body from its first row.
|
|
850
|
+
- `runningTotals={{ carryForwardLabel, broughtForwardLabel }}` adds carried-forward and brought-forward rows with the sums of the `sum` columns where the table breaks.
|
|
851
|
+
|
|
852
|
+
### Data tables
|
|
853
|
+
|
|
854
|
+
For long tables, pass rows as data: they travel to the engine as compact columns instead of thousands of elements (a 10,000-row table renders in about 0.6 s natively).
|
|
855
|
+
|
|
856
|
+
<!-- snippet: web/src/tests/docs/usage/tables.tsx#data-table -->
|
|
857
|
+
|
|
858
|
+
```tsx
|
|
859
|
+
import type { TableColumn } from '@rentnerkev/pdf'
|
|
860
|
+
|
|
861
|
+
interface Booking {
|
|
862
|
+
readonly date: string
|
|
863
|
+
readonly text: string
|
|
864
|
+
readonly cents: number
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
const bookings: Booking[] = Array.from({ length: 2_000 }, (_, index) => ({
|
|
868
|
+
date: `2026-${String((index % 12) + 1).padStart(2, '0')}-01`,
|
|
869
|
+
text: `Booking ${index + 1}`,
|
|
870
|
+
cents: ((index * 7_919) % 50_000) - 10_000,
|
|
871
|
+
}))
|
|
872
|
+
|
|
873
|
+
const columns = [
|
|
874
|
+
{ key: 'date', header: 'Date', width: '25mm' },
|
|
875
|
+
{ key: 'text', header: 'Text', width: '1fr' },
|
|
876
|
+
{
|
|
877
|
+
key: 'cents',
|
|
878
|
+
header: 'Amount',
|
|
879
|
+
width: '30mm',
|
|
880
|
+
align: 'right',
|
|
881
|
+
sum: true,
|
|
882
|
+
format: euro,
|
|
883
|
+
},
|
|
884
|
+
] satisfies TableColumn<Booking>[]
|
|
885
|
+
|
|
886
|
+
const ledger = (
|
|
887
|
+
<Table
|
|
888
|
+
data={bookings}
|
|
889
|
+
columns={columns}
|
|
890
|
+
cellClassName="px-2 py-0.5"
|
|
891
|
+
headerClassName="bg-gray-100 font-bold"
|
|
892
|
+
rowClassName="odd:bg-gray-50"
|
|
893
|
+
totals={{ label: 'Total', className: 'border-t font-bold' }}
|
|
894
|
+
runningTotals={{
|
|
895
|
+
carryForwardLabel: 'Carried forward',
|
|
896
|
+
broughtForwardLabel: 'Brought forward',
|
|
897
|
+
className: 'italic',
|
|
898
|
+
}}
|
|
899
|
+
className="text-xs"
|
|
900
|
+
/>
|
|
901
|
+
)
|
|
902
|
+
```
|
|
903
|
+
|
|
904
|
+
- `satisfies TableColumn<Row>[]` checks `key` against the row type; `format` and `sum` are only allowed on number properties. Columns with `format` or `sum` hold integer minor units; others show strings and `String(number)`.
|
|
905
|
+
- `rowClassName` (body rows), `headerClassName` (header row from the columns' `header`s), a column's `className` (its body cells), `totals: { label, className }`, a totals row with the grand totals once after the last row (`repeatFooter` repeats it on every page).
|
|
906
|
+
- Custom cell components and element rows inside a data table are not supported yet.
|
|
907
|
+
|
|
908
|
+
## Page templates and placeholders
|
|
909
|
+
|
|
910
|
+
<!-- snippet: web/src/tests/docs/usage/templates.tsx#templates -->
|
|
911
|
+
|
|
912
|
+
```tsx
|
|
913
|
+
import { Marker, Page, PageNumber, Text, TotalPages } from '@rentnerkev/pdf'
|
|
914
|
+
|
|
915
|
+
const stationery = await readFile('letterhead.pdf')
|
|
916
|
+
|
|
917
|
+
const report = (
|
|
918
|
+
<Page
|
|
919
|
+
size="A4"
|
|
920
|
+
className="px-[20mm] pt-[45mm] pb-[15mm]"
|
|
921
|
+
letterhead={{ src: stationery }}
|
|
922
|
+
header={
|
|
923
|
+
<Text className="border-b pb-1 text-xs text-gray-500">
|
|
924
|
+
<Marker name="chapter" />
|
|
925
|
+
</Text>
|
|
926
|
+
}
|
|
927
|
+
footer={
|
|
928
|
+
<Text className="text-right text-xs">
|
|
929
|
+
Page <PageNumber /> of <TotalPages />
|
|
930
|
+
</Text>
|
|
931
|
+
}
|
|
932
|
+
first={{ header: null }}
|
|
933
|
+
even={{
|
|
934
|
+
footer: (
|
|
935
|
+
<Text className="text-xs">
|
|
936
|
+
Page <PageNumber />
|
|
937
|
+
</Text>
|
|
938
|
+
),
|
|
939
|
+
}}
|
|
940
|
+
last={{ letterhead: null }}
|
|
941
|
+
>
|
|
942
|
+
{chapters}
|
|
943
|
+
</Page>
|
|
944
|
+
)
|
|
945
|
+
```
|
|
946
|
+
|
|
947
|
+
- `header` and `footer` repeat on every page the template creates, inside the page padding; the content takes the space between them.
|
|
948
|
+
- `first`, `odd`, `even` and `last` override `header`, `footer` or `letterhead` on those pages; `null` removes them. A page takes each from `last`, `first`, `odd`/`even`, then the template.
|
|
949
|
+
- `<PageNumber />`, `<TotalPages />` and `<Marker name />` go inside `Text` (or a `Cell`) and become real text after pagination. `marker="chapter"` on a `Text` sets the running marker (like CSS `string-set`); `<Marker select="first" | "last" | "start" | "first-except" />` shows it.
|
|
950
|
+
- `letterhead={{ src: pdfBytes, page: 0 }}` draws a page of an existing PDF behind the content: company stationery without re-creating it.
|
|
951
|
+
|
|
952
|
+
Every `Page` is a section. `numbering` restarts or restyles the page numbers (also as PDF page labels); `<TotalPages scope="section" />` counts the section's pages:
|
|
953
|
+
|
|
954
|
+
<!-- snippet: web/src/tests/docs/usage/templates.tsx#numbering -->
|
|
955
|
+
|
|
956
|
+
```tsx
|
|
957
|
+
const preface = (
|
|
958
|
+
<Page
|
|
959
|
+
size="A4"
|
|
960
|
+
className="p-page"
|
|
961
|
+
numbering={{ start: 1, format: 'lower-roman' }}
|
|
962
|
+
footer={
|
|
963
|
+
<Text className="text-center text-xs">
|
|
964
|
+
<PageNumber />
|
|
965
|
+
</Text>
|
|
966
|
+
}
|
|
967
|
+
>
|
|
968
|
+
<Text>Preface</Text>
|
|
969
|
+
</Page>
|
|
970
|
+
)
|
|
971
|
+
const body = (
|
|
972
|
+
<Page
|
|
973
|
+
size="A4"
|
|
974
|
+
className="p-page"
|
|
975
|
+
numbering={{ start: 1 }}
|
|
976
|
+
footer={
|
|
977
|
+
<Text className="text-center text-xs">
|
|
978
|
+
<PageNumber /> / <TotalPages scope="section" />
|
|
979
|
+
</Text>
|
|
980
|
+
}
|
|
981
|
+
>
|
|
982
|
+
{chapters}
|
|
983
|
+
</Page>
|
|
984
|
+
)
|
|
985
|
+
```
|
|
986
|
+
|
|
987
|
+
Formats: `'decimal'`, `'lower-roman'`, `'upper-roman'`, `'lower-alpha'`, `'upper-alpha'`.
|
|
988
|
+
|
|
989
|
+
## Images, SVG, links and bookmarks
|
|
990
|
+
|
|
991
|
+
<!-- snippet: web/src/tests/docs/usage/assets.tsx#images -->
|
|
992
|
+
|
|
993
|
+
```tsx
|
|
994
|
+
import { readFile } from 'node:fs/promises'
|
|
995
|
+
import { Image, Svg, View } from '@rentnerkev/pdf'
|
|
996
|
+
|
|
997
|
+
const logo = await readFile('logo.png') // PNG, JPEG, GIF or WebP bytes
|
|
998
|
+
const seal = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40">
|
|
999
|
+
<circle cx="20" cy="20" r="18" fill="#0f766e" />
|
|
1000
|
+
</svg>`
|
|
1001
|
+
|
|
1002
|
+
const header = (
|
|
1003
|
+
<View className="flex items-center justify-between">
|
|
1004
|
+
<Image src={logo} alt="Muster GmbH" className="w-32" />
|
|
1005
|
+
<Svg src={seal} alt="Seal" className="size-10" />
|
|
1006
|
+
<Image src={logo} alt="" className="h-20 w-40 object-contain" />
|
|
1007
|
+
</View>
|
|
1008
|
+
)
|
|
1009
|
+
```
|
|
1010
|
+
|
|
1011
|
+
- `Image` takes the file's bytes (`Uint8Array`, `Buffer` or `ArrayBuffer`): PNG (with alpha), JPEG (embedded unchanged), GIF (first frame) and WebP. RentnerPDF never reads paths or URLs: read or fetch them yourself.
|
|
1012
|
+
- Sizing works like an HTML `<img>` with Tailwind's preflight: natural size (one image pixel per CSS pixel), at most the container width, aspect ratio kept. With both sizes set, `object-contain`, `object-cover` and `object-*` positions fit it.
|
|
1013
|
+
- `Svg` takes markup or UTF-8 `.svg` bytes. Basic shapes, paths, gradients and clipping draw as vectors. Text uses the engine's fonts and stays selectable. Embedded PNG, JPEG, GIF and WebP images use `data:` URLs. Filters, masks, patterns, animation, `foreignObject` and external references produce `UNSUPPORTED_SVG_FEATURE` warnings. Strict mode turns these into `UNSUPPORTED_IMAGE` errors.
|
|
1014
|
+
- The same buffer used twice is embedded once, and the engine cache decodes the same logo once across renders.
|
|
1015
|
+
|
|
1016
|
+
<!-- snippet: web/src/tests/docs/usage/assets.tsx#links -->
|
|
1017
|
+
|
|
1018
|
+
```tsx
|
|
1019
|
+
import { Anchor, Link, Text } from '@rentnerkev/pdf'
|
|
1020
|
+
|
|
1021
|
+
const navigation = (
|
|
1022
|
+
<>
|
|
1023
|
+
<Text role="h1">Contract</Text>
|
|
1024
|
+
<Link href="#terms">
|
|
1025
|
+
<Text className="text-blue-700 underline">See the terms</Text>
|
|
1026
|
+
</Link>
|
|
1027
|
+
<Link href="https://example.com">
|
|
1028
|
+
<Text>example.com</Text>
|
|
1029
|
+
</Link>
|
|
1030
|
+
<Link href="mailto:info@example.com">
|
|
1031
|
+
<Text>info@example.com</Text>
|
|
1032
|
+
</Link>
|
|
1033
|
+
<Text role="h2" id="terms" className="break-before-page">
|
|
1034
|
+
Terms
|
|
1035
|
+
</Text>
|
|
1036
|
+
<Anchor id="appendix" bookmark="Appendix" />
|
|
1037
|
+
<Text role="h2" bookmark={false}>
|
|
1038
|
+
Not in the outline
|
|
1039
|
+
</Text>
|
|
1040
|
+
</>
|
|
1041
|
+
)
|
|
1042
|
+
```
|
|
1043
|
+
|
|
1044
|
+
- `Link` wraps boxes (inline links in a paragraph need inline text runs, which are not supported yet). `#id` jumps to a node with that `id` or an `Anchor`; ids also work from other documents (`contract.pdf#terms`).
|
|
1045
|
+
- `Text` with `role="h1"` … `"h6"` becomes a bookmark at its level. `bookmark="Title"` or `{ title, level }` adds or renames one; `false` removes it.
|
|
1046
|
+
|
|
1047
|
+
## Languages, scripts and typography
|
|
1048
|
+
|
|
1049
|
+
### Fonts and fallback
|
|
1050
|
+
|
|
1051
|
+
The bundled Noto Sans covers Latin, Greek and Cyrillic. For other scripts and emoji, register fonts that cover them; text falls back per character through the registered fonts.
|
|
1052
|
+
|
|
1053
|
+
<!-- snippet: web/src/tests/docs/usage/i18n.tsx#fonts -->
|
|
1054
|
+
|
|
1055
|
+
```tsx
|
|
1056
|
+
import { readFile } from 'node:fs/promises'
|
|
1057
|
+
import { createEngine, Document, Page, Text, View } from '@rentnerkev/pdf'
|
|
1058
|
+
|
|
1059
|
+
// Text falls back per character: the font-family stack, the default family
|
|
1060
|
+
// (the first registered font's), every registered font in this order, then
|
|
1061
|
+
// the bundled Noto Sans. Emoji prefer color fonts.
|
|
1062
|
+
const engine = await createEngine({
|
|
1063
|
+
fonts: [
|
|
1064
|
+
await readFile('fonts/NotoSansHebrew-Regular.ttf'),
|
|
1065
|
+
await readFile('fonts/NotoColorEmoji.ttf'), // COLR or CBDT
|
|
1066
|
+
await readFile('fonts/OpenSans-Variable.ttf'), // one file, every weight
|
|
1067
|
+
],
|
|
1068
|
+
})
|
|
1069
|
+
```
|
|
1070
|
+
|
|
1071
|
+
- **Fallback order:** the `font-family` stack (`font-['Inter',sans-serif]`), the default family (the first registered font's), every other registered font in registration order, then the bundled Noto Sans. Emoji (`😀`, `👍🏽`, `🇩🇪`, `1️⃣`, joined sequences) prefer color fonts and stay one glyph; other characters prefer fonts without color glyphs. Characters no font covers draw as empty boxes and produce a `MISSING_GLYPH` warning; `strict` makes it a `FONT_NOT_FOUND` error.
|
|
1072
|
+
- **Faces:** a family's faces are separate files; `font-bold`, `italic` and `font-stretch-*` pick them by CSS font matching. There is no synthetic bold or italic and no system font.
|
|
1073
|
+
- **Scripts:** Arabic, Hebrew, Devanagari, Thai, Chinese and other scripts are shaped with their script and the text's `lang` (for language-specific forms). Thai, Lao, Khmer and Myanmar break between dictionary words; Chinese and Japanese between characters, never before closing punctuation.
|
|
1074
|
+
|
|
1075
|
+
A variable font is registered once and serves every weight, width and slant its axes cover; `font-*`, `font-stretch-*` and `italic` select the instance, and `fontVariationSettings` (or `[font-variation-settings:'wght'_650]`) sets axes directly:
|
|
1076
|
+
|
|
1077
|
+
<!-- snippet: web/src/tests/docs/usage/i18n.tsx#variable -->
|
|
1078
|
+
|
|
1079
|
+
```tsx
|
|
1080
|
+
const weights = (
|
|
1081
|
+
<View className="font-['Open_Sans']">
|
|
1082
|
+
<Text className="font-light">Light</Text>
|
|
1083
|
+
<Text className="font-semibold font-stretch-condensed">
|
|
1084
|
+
SemiBold Condensed
|
|
1085
|
+
</Text>
|
|
1086
|
+
<Text style={{ fontVariationSettings: "'wght' 650" }}>Settings</Text>
|
|
1087
|
+
</View>
|
|
1088
|
+
)
|
|
1089
|
+
```
|
|
1090
|
+
|
|
1091
|
+
### Right-to-left
|
|
1092
|
+
|
|
1093
|
+
`dir="rtl"` (on `Document`, `View`, `Text`, `Table` or `Cell`) works like HTML's `dir`:
|
|
1094
|
+
|
|
1095
|
+
<!-- snippet: web/src/tests/docs/usage/i18n.tsx#direction -->
|
|
1096
|
+
|
|
1097
|
+
```tsx
|
|
1098
|
+
const invoice = (
|
|
1099
|
+
<Document lang="he" dir="rtl">
|
|
1100
|
+
<Page className="p-page">
|
|
1101
|
+
{/* text-start is the right edge, flex rows run right to left */}
|
|
1102
|
+
<Text className="text-start text-lg font-bold">חשבונית 2026</Text>
|
|
1103
|
+
<View className="flex flex-row justify-between border-b ps-4">
|
|
1104
|
+
<Text>סה״כ</Text>
|
|
1105
|
+
<Text>₪ 1,234.00</Text>
|
|
1106
|
+
</View>
|
|
1107
|
+
<Text dir="ltr" lang="en">
|
|
1108
|
+
Reference: INV-2026-0042 🎉
|
|
1109
|
+
</Text>
|
|
1110
|
+
</Page>
|
|
1111
|
+
</Document>
|
|
1112
|
+
)
|
|
1113
|
+
```
|
|
1114
|
+
|
|
1115
|
+
- It sets the paragraph direction (`text-start`/`text-end`, the order of mixed text), runs flex rows, grid and table columns from the right, maps logical sides (`ps-*`, `ms-*`, `border-s`, `start-*`) and activates the `rtl:`/`ltr:` variants. `dir="auto"` takes the direction of the first strong character: per line of a `Text`, from the first text inside for a container.
|
|
1116
|
+
- Without any `dir`, layout runs left to right and every line of text detects its own direction, so an Arabic paragraph is still right-aligned by `text-start`.
|
|
1117
|
+
- Copy and paste, search and text extraction read right-to-left text in logical order.
|
|
1118
|
+
|
|
1119
|
+
### Hyphenation and justification
|
|
1120
|
+
|
|
1121
|
+
Lines break greedily at spaces and other opportunities. Three class families (inherited, like their CSS properties) change that:
|
|
1122
|
+
|
|
1123
|
+
- `hyphens-auto` hyphenates words with the patterns of the text's `lang` (from the text, a view, a table or cell, or the `Document`). The npm builds embed German, English, Spanish, French and Italian patterns. `en-GB` uses the English (US) patterns. The optional Rust feature `hyphenation-dutch` adds Dutch patterns and is **experimental**. Without patterns for the language the class has no effect and warns `NO_EFFECT`. Soft hyphens (U+00AD, `` in a JSX string) always break with a hyphen (`hyphens-manual`, the default) unless `hyphens-none` is set. Copied or searched text gives the word without the hyphen. Right-to-left text is not hyphenated.
|
|
1124
|
+
- `text-justify` stretches the spaces of every line but the last; letters are never spaced apart.
|
|
1125
|
+
- `text-pretty` chooses the breaks of the whole paragraph together (Knuth–Plass): even lines, few hyphens, no lonely last word. `text-balance` gives every line of a heading about the same length.
|
|
1126
|
+
|
|
1127
|
+
Typed `style` has `hyphens`, `textAlign: 'justify'` and `textWrapStyle: 'pretty' | 'balance'`.
|
|
1128
|
+
|
|
1129
|
+
<!-- snippet: web/src/tests/docs/usage/styling.tsx#line-breaking -->
|
|
1130
|
+
|
|
1131
|
+
```tsx
|
|
1132
|
+
const terms = (
|
|
1133
|
+
<View lang="de-DE" className="flex flex-col gap-2 text-sm">
|
|
1134
|
+
<Text className="hyphens-auto text-justify">
|
|
1135
|
+
Die Zahlungserinnerung betrifft Rechnungsbeträge aus Lieferungen und
|
|
1136
|
+
Leistungen des Abrechnungszeitraums.
|
|
1137
|
+
</Text>
|
|
1138
|
+
<Text lang="en-GB" className="hyphens-auto text-pretty">
|
|
1139
|
+
English text in the same document uses the English patterns.
|
|
1140
|
+
</Text>
|
|
1141
|
+
<Text className="text-xl font-bold text-balance">
|
|
1142
|
+
Bericht über die Prüfung des Jahresabschlusses
|
|
1143
|
+
</Text>
|
|
1144
|
+
<Text>{'Soft hyphens break here: Liefer\u00ADbedingungen'}</Text>
|
|
1145
|
+
</View>
|
|
1146
|
+
)
|
|
1147
|
+
```
|
|
1148
|
+
|
|
1149
|
+
## PDF/A and attachments
|
|
1150
|
+
|
|
1151
|
+
`standard` makes the PDF conform to PDF/A-2b, 2u, 3b or 3u (`'pdf-a-2b'` … `'pdf-a-3u'`; `'pdf-ua-1'` is [accessibility](#accessibility)): the engine writes the sRGB output intent and the conformance level into the metadata and validates the document while writing it. What the standard forbids fails with `STANDARD_VIOLATION` and the path instead of producing an invalid file: a missing `creationDate`, letterheads (pages of other PDFs), characters no font covers, attachments in PDF/A-2, attachments without `mimeType` or `description` in PDF/A-3. `attachments` embed files, in PDF/A-3 or without a standard:
|
|
1152
|
+
|
|
1153
|
+
<!-- snippet: web/src/tests/docs/usage/standards.tsx#standards -->
|
|
1154
|
+
|
|
1155
|
+
```tsx
|
|
1156
|
+
const archived = (
|
|
1157
|
+
<Document
|
|
1158
|
+
title="Annual report 2026"
|
|
1159
|
+
lang="en-GB"
|
|
1160
|
+
creationDate="2026-12-01T09:30:00+01:00" // PDF/A needs a date
|
|
1161
|
+
standard="pdf-a-3b"
|
|
1162
|
+
attachments={[
|
|
1163
|
+
{
|
|
1164
|
+
name: 'revenue.csv',
|
|
1165
|
+
src: csv, // bytes, or a string embedded as UTF-8
|
|
1166
|
+
mimeType: 'text/csv',
|
|
1167
|
+
description: 'Monthly revenue behind the charts',
|
|
1168
|
+
relationship: 'Data',
|
|
1169
|
+
},
|
|
1170
|
+
]}
|
|
1171
|
+
>
|
|
1172
|
+
<Page className="p-page">
|
|
1173
|
+
<Text role="h1">Annual report 2026</Text>
|
|
1174
|
+
</Page>
|
|
1175
|
+
</Document>
|
|
1176
|
+
)
|
|
1177
|
+
```
|
|
1178
|
+
|
|
1179
|
+
`relationship` (`Source`, `Data`, `Alternative`, `Supplement`, `Unspecified`) is written in PDF/A-3; `modificationDate` is optional (PDF/A-3 falls back to `creationDate`, the engine never reads the clock). Attachments are embedded as opaque bytes; their names have at most 255 bytes and no slashes. For electronic invoices, `facturX={{ conformanceLevel: 'EN 16931' }}` adds the Factur-X / ZUGFeRD descriptor; see the [ZUGFeRD recipe](recipes/zugferd.md). The same props work with React and the `document()` factory.
|
|
1180
|
+
|
|
1181
|
+
## Accessibility
|
|
1182
|
+
|
|
1183
|
+
`tagged` on `Document` writes a structure tree, so screen readers, reflow and text export follow headings, lists and tables in reading order. `standard="pdf-ua-1"` also makes the file a PDF/UA-1 document (ISO 14289-1): tagged, with the title in the viewer's title bar and the PDF/UA identification in its metadata.
|
|
1184
|
+
|
|
1185
|
+
<!-- snippet: web/src/tests/docs/usage/accessibility.tsx#tagged -->
|
|
1186
|
+
|
|
1187
|
+
```tsx
|
|
1188
|
+
import {
|
|
1189
|
+
Cell,
|
|
1190
|
+
Document,
|
|
1191
|
+
Image,
|
|
1192
|
+
Page,
|
|
1193
|
+
PageNumber,
|
|
1194
|
+
Row,
|
|
1195
|
+
Svg,
|
|
1196
|
+
Table,
|
|
1197
|
+
Text,
|
|
1198
|
+
View,
|
|
1199
|
+
} from '@rentnerkev/pdf'
|
|
1200
|
+
|
|
1201
|
+
const report = (
|
|
1202
|
+
<Document title="Annual report" lang="en" standard="pdf-ua-1">
|
|
1203
|
+
<Page
|
|
1204
|
+
className="p-page"
|
|
1205
|
+
footer={
|
|
1206
|
+
<Text className="text-xs">
|
|
1207
|
+
Page <PageNumber />
|
|
1208
|
+
</Text>
|
|
1209
|
+
}
|
|
1210
|
+
>
|
|
1211
|
+
<Text role="h1">Annual report</Text>
|
|
1212
|
+
<Text>Revenue grew in every region.</Text>
|
|
1213
|
+
<Svg src={chart} alt="Bar chart: revenue rose each quarter" />
|
|
1214
|
+
<Image src={logo} alt="" className="w-16" />
|
|
1215
|
+
<View role="list">
|
|
1216
|
+
<View role="listitem" className="flex gap-2">
|
|
1217
|
+
<Text role="label">1.</Text>
|
|
1218
|
+
<Text>The north opened two sites.</Text>
|
|
1219
|
+
</View>
|
|
1220
|
+
</View>
|
|
1221
|
+
<Table>
|
|
1222
|
+
<Row header>
|
|
1223
|
+
<Cell>Region</Cell>
|
|
1224
|
+
<Cell>Revenue</Cell>
|
|
1225
|
+
</Row>
|
|
1226
|
+
<Row>
|
|
1227
|
+
<Cell role="th">North</Cell>
|
|
1228
|
+
<Cell>1,200 €</Cell>
|
|
1229
|
+
</Row>
|
|
1230
|
+
</Table>
|
|
1231
|
+
<Text lang="de">Vielen Dank.</Text>
|
|
1232
|
+
</Page>
|
|
1233
|
+
</Document>
|
|
1234
|
+
)
|
|
1235
|
+
```
|
|
1236
|
+
|
|
1237
|
+
- **Reading order** is the order of your elements, not where they end up on the page (`order-*`, absolute positioning). A paragraph or table that continues on the next page stays one element.
|
|
1238
|
+
- **Roles:** a `Text` is a paragraph unless its `role` says `h1`–`h6`, `caption`, `blockquote`, `code` or `label`; a `View` has no element of its own unless its `role` is `section`, `article`, `part`, `div`, `blockquote`, `figure` (with `alt`), `list`, `listitem` or a text role. Unknown roles are `UNKNOWN_ROLE` warnings.
|
|
1239
|
+
- **Images and SVGs** are figures and need `alt`. `alt=""` or `role="artifact"` marks decoration. A missing `alt` is a `MISSING_ALT_TEXT` warning, an `INVALID_DOCUMENT` error in strict mode and a `STANDARD_VIOLATION` in PDF/UA-1. A `View role="figure" alt="…"` describes a chart built from several elements.
|
|
1240
|
+
- **Tables:** header rows hold column headers; `<Cell role="th">` in a body row is a row header. `scope="col" | "row" | "both"` overrides that. `role="presentation"` on a `Table` that only arranges content leaves the table structure out.
|
|
1241
|
+
- **Artifacts:** headers, footers and their page numbers, page backgrounds, borders and backgrounds of boxes, header rows repeated on later pages and running totals are left out of the structure, as is anything with `role="artifact"`.
|
|
1242
|
+
- **Links** are described by their text (or the `alt` of their images); **`lang`** on any node marks text in another language.
|
|
1243
|
+
- **PDF/UA-1 needs** `title`, `lang`, alt text for every image that is not decorative and fonts that have every character; letterheads (embedded PDF pages) are not allowed. CI validates the output with veraPDF.
|
|
1244
|
+
|
|
1245
|
+
## Browser preview
|
|
1246
|
+
|
|
1247
|
+
In browsers, the WebAssembly engine renders in a Web Worker, so the page stays responsive while a document renders. `@rentnerkev/pdf/worker` connects the page and the worker; `usePdf()` and `<PdfPreview>` from `@rentnerkev/pdf/react` keep a live preview in a React app.
|
|
1248
|
+
|
|
1249
|
+
**Experimental:** `@rentnerkev/pdf/worker` (its API and protocol), `usePdf()` and `<PdfPreview>` are exempt from SemVer in 1.x until promoted. A worker engine reports its engine's version in `version`, like `Engine.version`.
|
|
1250
|
+
|
|
1251
|
+
The worker module:
|
|
1252
|
+
|
|
1253
|
+
<!-- snippet: web/src/tests/docs/usage/preview/pdf.worker.ts -->
|
|
1254
|
+
|
|
1255
|
+
```ts
|
|
1256
|
+
// pdf.worker.ts runs in the Web Worker and renders with WebAssembly.
|
|
1257
|
+
import { serveRenderWorker } from '@rentnerkev/pdf/worker'
|
|
1258
|
+
|
|
1259
|
+
serveRenderWorker()
|
|
1260
|
+
```
|
|
1261
|
+
|
|
1262
|
+
The document, written with the own JSX runtime (or the factories):
|
|
1263
|
+
|
|
1264
|
+
<!-- snippet: web/src/tests/docs/usage/preview/invoice-document.tsx -->
|
|
1265
|
+
|
|
1266
|
+
```tsx
|
|
1267
|
+
/** @jsxImportSource @rentnerkev/pdf */
|
|
1268
|
+
// invoice-document.tsx: documents for the worker engine use the own JSX
|
|
1269
|
+
// runtime (or the factories); React elements do not cross to the worker.
|
|
1270
|
+
import { Document, Page, Text } from '@rentnerkev/pdf'
|
|
1271
|
+
|
|
1272
|
+
export interface Draft {
|
|
1273
|
+
readonly number: string
|
|
1274
|
+
readonly customer: string
|
|
1275
|
+
}
|
|
1276
|
+
|
|
1277
|
+
export function invoiceDocument(draft: Draft) {
|
|
1278
|
+
return (
|
|
1279
|
+
<Document title={`Invoice ${draft.number}`} lang="en">
|
|
1280
|
+
<Page size="A4" className="p-page text-sm">
|
|
1281
|
+
<Text role="h1" className="text-2xl font-bold">
|
|
1282
|
+
Invoice {draft.number}
|
|
1283
|
+
</Text>
|
|
1284
|
+
<Text>Customer: {draft.customer}</Text>
|
|
1285
|
+
</Page>
|
|
1286
|
+
</Document>
|
|
1287
|
+
)
|
|
1288
|
+
}
|
|
1289
|
+
```
|
|
1290
|
+
|
|
1291
|
+
The preview in the React app:
|
|
1292
|
+
|
|
1293
|
+
<!-- snippet: web/src/tests/docs/usage/preview/preview.tsx#preview -->
|
|
1294
|
+
|
|
1295
|
+
```tsx
|
|
1296
|
+
import { PdfPreview, usePdf } from '@rentnerkev/pdf/react'
|
|
1297
|
+
import { createWorkerEngine, type WorkerEngine } from '@rentnerkev/pdf/worker'
|
|
1298
|
+
import { invoiceDocument, type Draft } from './invoice-document.tsx'
|
|
1299
|
+
|
|
1300
|
+
// One worker engine per page, created on first use, so server rendering
|
|
1301
|
+
// never creates a worker.
|
|
1302
|
+
let engine: Promise<WorkerEngine> | undefined
|
|
1303
|
+
export const pdfEngine = (): Promise<WorkerEngine> =>
|
|
1304
|
+
(engine ??= createWorkerEngine({
|
|
1305
|
+
worker: new Worker(new URL('./pdf.worker.ts', import.meta.url), {
|
|
1306
|
+
type: 'module',
|
|
1307
|
+
}),
|
|
1308
|
+
}))
|
|
1309
|
+
|
|
1310
|
+
// The browser's PDF viewer in an <iframe>; it renders again once the draft
|
|
1311
|
+
// has stayed unchanged for 200 ms and keeps the previous PDF meanwhile.
|
|
1312
|
+
export function InvoicePreview({ draft }: { draft: Draft }) {
|
|
1313
|
+
return (
|
|
1314
|
+
<PdfPreview
|
|
1315
|
+
document={invoiceDocument(draft)}
|
|
1316
|
+
engine={pdfEngine}
|
|
1317
|
+
title={`Invoice ${draft.number}`}
|
|
1318
|
+
className="h-full w-full"
|
|
1319
|
+
fallback={<p>Rendering …</p>}
|
|
1320
|
+
/>
|
|
1321
|
+
)
|
|
1322
|
+
}
|
|
1323
|
+
|
|
1324
|
+
// The hook behind it: status, page count, warnings, errors and the URL.
|
|
1325
|
+
export function InvoiceDownload({ draft }: { draft: Draft }) {
|
|
1326
|
+
const { state } = usePdf(invoiceDocument(draft), { engine: pdfEngine })
|
|
1327
|
+
if (state.status === 'failed') return <p>{String(state.error)}</p>
|
|
1328
|
+
if (state.url === undefined) return <p>Rendering …</p>
|
|
1329
|
+
return (
|
|
1330
|
+
<a href={state.url} download={`invoice-${draft.number}.pdf`}>
|
|
1331
|
+
Download ({state.pageCount} pages)
|
|
1332
|
+
</a>
|
|
1333
|
+
)
|
|
1334
|
+
}
|
|
1335
|
+
```
|
|
1336
|
+
|
|
1337
|
+
- `createWorkerEngine({ worker, …options })` takes the engine options of `createEngine()` except `backend` and `threads` (fonts as bytes, `theme`, `limits`, `strict`, caches, `wasmModule`) and returns an engine with `render()` and `renderDetailed()`: the same bytes, warnings and errors (codes, IR paths, JSX sources) as `createEngine({ backend: 'wasm' })`. `worker` is a `Worker` that calls `serveRenderWorker()`, or a `MessagePort`.
|
|
1338
|
+
- Components are evaluated on the page; the worker receives the encoded document and transfers the PDF back. One render at a time runs in the worker, in call order. An aborted `signal` rejects at once and a waiting render never reaches the worker; a render already in the worker finishes there and its result is dropped. `registerFont()` and `close()` work as on [`createEngine()`](#fonts-later-and-closing); `close()` also stops the worker.
|
|
1339
|
+
- `usePdf(document, { engine, debounceMs })` renders when the document changes in content (not in identity), once it has stayed unchanged for `debounceMs` (200 by default); a newer document aborts the render in progress. `state` holds `status` (`idle`, `rendering`, `done`, `failed`), the latest `pdf`, its object `url` (revoked when replaced and on unmount), `pageCount`, `warnings`, `diagnostics` and `error`; the previous PDF stays while a newer one renders or fails. `engine` may be any object with `renderDetailed()` (a `createEngine()` engine too), a promise of one, or a function called when a render starts; keep its identity.
|
|
1340
|
+
- `<PdfPreview>` shows the URL in an `<iframe>` (a fresh frame per PDF) and passes other props to it; `fallback` shows until the first PDF.
|
|
1341
|
+
|
|
1342
|
+
Not in this release:
|
|
1343
|
+
|
|
1344
|
+
- **Bundler integration.** The worker and `createEngine({ backend: 'wasm' })` load the wasm-bindgen glue from `./pkg/` next to the loader and the bundled fonts from `../fonts/`. Serve those assets with the browser bundle as the [playground build](../scripts/playground/build.ts) does. `@rentnerkev/pdf/wasm-binary` exposes the `.wasm` file for tools that handle the module as an asset. Pass that module via `wasmModule` and supply `fonts` with `defaultFont: false` to replace the bundled fonts.
|
|
1345
|
+
- **React documents in the worker:** documents written with `@rentnerkev/pdf/react` components render on the server only; previews use the own JSX runtime or the factories.
|
|
1346
|
+
- **Interrupting a running render** inside the worker (it needs `SharedArrayBuffer` and cross-origin isolation).
|
|
1347
|
+
- In TanStack Start and other Nitro apps, the Vite plugin (**experimental**: it follows Nitro's fast-moving module API) blocks engine imports in client code; `rentnerPdf({ client: 'allow' })` allows `@rentnerkev/pdf` and `@rentnerkev/pdf/react` there for previews.
|
|
1348
|
+
|
|
1349
|
+
## Errors, warnings and diagnostics
|
|
1350
|
+
|
|
1351
|
+
### Errors
|
|
1352
|
+
|
|
1353
|
+
Rendering fails with a `RentnerPdfError` for invalid documents and resources; errors your components throw pass through unchanged (with a `componentStack`).
|
|
1354
|
+
|
|
1355
|
+
<!-- snippet: web/src/tests/docs/usage/errors.tsx#errors -->
|
|
1356
|
+
|
|
1357
|
+
```tsx
|
|
1358
|
+
import { render, RentnerPdfError } from '@rentnerkev/pdf'
|
|
1359
|
+
|
|
1360
|
+
function describeError(error: unknown): string {
|
|
1361
|
+
if (!(error instanceof RentnerPdfError)) return String(error)
|
|
1362
|
+
// error.code: 'INVALID_DOCUMENT', 'UNSUPPORTED_IMAGE', 'LIMIT_EXCEEDED', …
|
|
1363
|
+
// error.path: the IR path, for example 'pages[0].children[0]'
|
|
1364
|
+
// error.source: where the element was written (development JSX runtime)
|
|
1365
|
+
// error.componentStack: the components that were rendering
|
|
1366
|
+
return [`${error.code}: ${error.message}`, error.componentStack]
|
|
1367
|
+
.filter(Boolean)
|
|
1368
|
+
.join('\n')
|
|
1369
|
+
}
|
|
1370
|
+
|
|
1371
|
+
let report = ''
|
|
1372
|
+
try {
|
|
1373
|
+
// Text belongs inside <Text>, not directly inside a <View>.
|
|
1374
|
+
await render(
|
|
1375
|
+
<Document>
|
|
1376
|
+
<Page>
|
|
1377
|
+
<View>Loose text</View>
|
|
1378
|
+
</Page>
|
|
1379
|
+
</Document>,
|
|
1380
|
+
)
|
|
1381
|
+
} catch (error) {
|
|
1382
|
+
report = describeError(error)
|
|
1383
|
+
}
|
|
1384
|
+
```
|
|
1385
|
+
|
|
1386
|
+
| Code | Meaning |
|
|
1387
|
+
| -------------------- | -------------------------------------------------------------------------------------------- |
|
|
1388
|
+
| `INVALID_DOCUMENT` | The tree breaks a rule: text outside `Text`, an unknown prop, a duplicate `id`, a bad `href` |
|
|
1389
|
+
| `FONT_NOT_FOUND` | Text to draw but no font registered (`defaultFont: false` without `fonts`) |
|
|
1390
|
+
| `UNSUPPORTED_FONT` | Font bytes that cannot be read |
|
|
1391
|
+
| `UNSUPPORTED_IMAGE` | Image, SVG or letterhead bytes that cannot be decoded |
|
|
1392
|
+
| `UNSUPPORTED_CLASS` | A class or value problem in `strict` mode |
|
|
1393
|
+
| `LIMIT_EXCEEDED` | A [limit](#limits) was hit |
|
|
1394
|
+
| `INCOMPLETE_RENDER` | The React render did not complete (an error or pending `<Suspense>` boundary) |
|
|
1395
|
+
| `ABORTED` | A `signal` (or `timeoutMs` of `renderToPdf`) stopped the render, or `close()` cancelled it |
|
|
1396
|
+
| `ENGINE_CLOSED` | A method of an engine that [`close()`](#fonts-later-and-closing) released |
|
|
1397
|
+
| `STANDARD_VIOLATION` | The selected [standard](#pdfa-and-attachments) forbids something in the document |
|
|
1398
|
+
| `INTERNAL` | A bug in RentnerPDF; please report it |
|
|
1399
|
+
|
|
1400
|
+
`error.path` is the IR path of the node (`pages[0].children[2]`). With the development JSX runtime `error.source` names the file and line; on the React path, development builds add the component stack. A [strict mode](#strict-mode) error names the warning it was made from in `error.warning`.
|
|
1401
|
+
|
|
1402
|
+
### Warnings
|
|
1403
|
+
|
|
1404
|
+
Problems the engine can work around are warnings in `renderDetailed()` (and `renderToPdfDetailed()`); `render()` ignores them. A problem that repeats is reported once, at its first node.
|
|
1405
|
+
|
|
1406
|
+
<!-- snippet: web/src/tests/docs/usage/errors.tsx#warnings -->
|
|
1407
|
+
|
|
1408
|
+
```tsx
|
|
1409
|
+
import { createEngine } from '@rentnerkev/pdf'
|
|
1410
|
+
|
|
1411
|
+
const engine = await createEngine()
|
|
1412
|
+
const typo = (
|
|
1413
|
+
<Document>
|
|
1414
|
+
<Page className="p-page">
|
|
1415
|
+
<Text className="pading-4 hover:underline">Hello</Text>
|
|
1416
|
+
</Page>
|
|
1417
|
+
</Document>
|
|
1418
|
+
)
|
|
1419
|
+
const { warnings } = await engine.renderDetailed(typo)
|
|
1420
|
+
// [{ code: 'UNKNOWN_CLASS', className: 'pading-4', suggestion: 'p-4', path, source, … },
|
|
1421
|
+
// { code: 'IGNORED_VARIANT', className: 'hover:underline', path, source, … }]
|
|
1422
|
+
```
|
|
1423
|
+
|
|
1424
|
+
Each warning includes a `code`, a `message` and the node's `path`. Class warnings can also include `className` and a `suggestion`. The development JSX runtime can add the `source`. Warning codes include `UNKNOWN_CLASS` (with a `suggestion` if a close match exists), `INVALID_VALUE`, `UNSUPPORTED_CLASS`, `IGNORED_VARIANT`, `NO_EFFECT`, `MISSING_GLYPH` and `UNSUPPORTED_SVG_FEATURE`. `engine.themeWarnings` uses `INVALID_THEME`. Tagged documents also use `UNKNOWN_ROLE` and `MISSING_ALT_TEXT`.
|
|
1425
|
+
|
|
1426
|
+
### Strict mode
|
|
1427
|
+
|
|
1428
|
+
`createEngine({ strict: true })` turns `UNKNOWN_CLASS`, `INVALID_VALUE` and `UNSUPPORTED_CLASS` into `UNSUPPORTED_CLASS` errors. `MISSING_GLYPH` becomes `FONT_NOT_FOUND`, and `UNSUPPORTED_SVG_FEATURE` becomes `UNSUPPORTED_IMAGE`. In tagged documents `UNKNOWN_ROLE` and `MISSING_ALT_TEXT` become `INVALID_DOCUMENT`. `IGNORED_VARIANT` and `NO_EFFECT` stay warnings, so components shared with a web UI also render. The `warning` field on a strict-mode error identifies the original warning code.
|
|
1429
|
+
|
|
1430
|
+
<!-- snippet: web/src/tests/docs/usage/errors.tsx#strict -->
|
|
1431
|
+
|
|
1432
|
+
```tsx
|
|
1433
|
+
const strict = await createEngine({ strict: true })
|
|
1434
|
+
let strictCode = ''
|
|
1435
|
+
let strictWarning = ''
|
|
1436
|
+
try {
|
|
1437
|
+
await strict.render(typo)
|
|
1438
|
+
} catch (error) {
|
|
1439
|
+
// UNSUPPORTED_CLASS for 'pading-4'; IGNORED_VARIANT stays a warning
|
|
1440
|
+
if (error instanceof RentnerPdfError) {
|
|
1441
|
+
strictCode = error.code
|
|
1442
|
+
strictWarning = error.warning ?? '' // 'UNKNOWN_CLASS', the warning it was
|
|
1443
|
+
}
|
|
1444
|
+
}
|
|
1445
|
+
```
|
|
1446
|
+
|
|
1447
|
+
### Wrap diagnostics
|
|
1448
|
+
|
|
1449
|
+
`renderDetailed()` also explains page breaks the layout had to make: which node moved to the next page or was forced onto one, on which page (`pageIndex`, from 0: not the printed page number) and why.
|
|
1450
|
+
|
|
1451
|
+
<!-- snippet: web/src/tests/docs/usage/errors.tsx#diagnostics -->
|
|
1452
|
+
|
|
1453
|
+
```tsx
|
|
1454
|
+
const { diagnostics } = await engine.renderDetailed(
|
|
1455
|
+
<Document>
|
|
1456
|
+
<Page size="A5" className="p-page">
|
|
1457
|
+
<View className="h-[150mm]" />
|
|
1458
|
+
<Keep>
|
|
1459
|
+
<Text role="h2">Payment terms</Text>
|
|
1460
|
+
<Text>
|
|
1461
|
+
{'Payable within 14 days without deduction. '.repeat(6)}
|
|
1462
|
+
</Text>
|
|
1463
|
+
</Keep>
|
|
1464
|
+
</Page>
|
|
1465
|
+
</Document>,
|
|
1466
|
+
)
|
|
1467
|
+
// [{ pageIndex: 0, reason: 'KEEP_TOGETHER', path: 'pages[0].children[1]',
|
|
1468
|
+
// message: '…', source: { fileName, lineNumber, columnNumber } }]
|
|
1469
|
+
```
|
|
1470
|
+
|
|
1471
|
+
Reasons: `KEEP_WITH_NEXT`, `KEEP_TOGETHER`, `KEEP_TOGETHER_TOO_TALL` (split anyway), `WIDOWS_ORPHANS`, `DOES_NOT_FIT` (also where a table breaks) and `FORCED_OVERSIZE` (taller than a page, overflows).
|
|
1472
|
+
|
|
1473
|
+
## Limits
|
|
1474
|
+
|
|
1475
|
+
### Resource limits
|
|
1476
|
+
|
|
1477
|
+
Document content, images, fonts, SVGs and letterheads may come from untrusted users. The engine configuration comes from you. Each render in `renderMany()` receives its own budget. A document that exceeds a budget fails with `LIMIT_EXCEEDED` and the path in the document.
|
|
1478
|
+
|
|
1479
|
+
| Limit | Option | Default | Guards against |
|
|
1480
|
+
| ----------------------------------------------------------------------- | ------------------------- | ------------- | ------------------------------------------------------- |
|
|
1481
|
+
| Encoded document (IR JSON or React markup) | `maxInputBytes` | 256 MiB | Oversized requests |
|
|
1482
|
+
| Pages, including pages created by overflow | `maxPages` | 100,000 | Runaway pagination |
|
|
1483
|
+
| Content nodes (table rows and cells count) | `maxNodes` | 10,000,000 | Huge trees |
|
|
1484
|
+
| Nesting depth below a page | `maxDepth` | 60 | Deep recursion |
|
|
1485
|
+
| Bytes of one `className` | `maxClassNameBytes` | 16 KiB | Expensive class parsing |
|
|
1486
|
+
| Classes in one `className` | `maxClasses` | 512 | Expensive class parsing |
|
|
1487
|
+
| Asset bytes of one render (images, SVGs, PDFs, attachments, table data) | `maxAssetBytes` | 256 MiB | Memory |
|
|
1488
|
+
| Pixels of one image, read from its header before decoding | `maxImagePixels` | 100,000,000 | Decompression bombs |
|
|
1489
|
+
| Combined raster pixels of one render | `maxTotalImagePixels` | 1,000,000,000 | Cumulative image decoding and memory |
|
|
1490
|
+
| Estimated work of parsing and embedding letterheads | `maxLetterheadParseBytes` | 256 MiB | Expensive object traversal and stream expansion |
|
|
1491
|
+
| Elements of one SVG as it will be drawn¹ | `maxSvgElements` | 200,000 | SVG bombs |
|
|
1492
|
+
| UTF-8 bytes of one paragraph or table cell | `maxTextBytes` | 4 MiB | Shaping memory (about 20 bytes per byte of text) |
|
|
1493
|
+
| Bytes of one font file, checked when the engine registers it | `maxFontBytes` | 64 MiB | Font memory; `createEngine()` or `registerFont()` fails |
|
|
1494
|
+
|
|
1495
|
+
¹ The converter counts each expanded element instance, including `<use>` copies and referenced clip geometry. It also charges each style rule, each group of up to 32 path segments or dash entries and each group of up to 32 gradient stops per painted element. All text processed for one SVG shares `maxTextBytes`.
|
|
1496
|
+
|
|
1497
|
+
The total pixel budget counts each referenced asset buffer once, including raster images within SVGs. Repeated uses of the same SVG image node share its decoder and pixel charge. For GIFs and extended WebP images, the engine counts the largest pixel area it reads from the canvas and frame headers. The letterhead budget counts each referenced PDF buffer and the work of embedding each selected page. Cached assets use the same budgets as newly loaded assets. These options work in the native, WebAssembly and worker engines.
|
|
1498
|
+
|
|
1499
|
+
- `createEngine({ limits: { maxPages: 500 } })` overrides single limits; absent ones keep their defaults, `Infinity` lifts one. Unknown names throw a `TypeError` and invalid values a `RangeError` before an engine exists.
|
|
1500
|
+
- `limits: 'unlimited'` lifts every limit above, for trusted batch jobs only.
|
|
1501
|
+
- Time is not a limit: pass a `signal` (`AbortSignal.timeout(10_000)`), which stops the render at its next page or paragraph with `ABORTED` ([cancellation](#cancellation)). The engine's `threads` bound the CPU a burst of requests can take.
|
|
1502
|
+
|
|
1503
|
+
These fixed bounds also apply with `limits: 'unlimited'`.
|
|
1504
|
+
|
|
1505
|
+
| Bound | Value | Result |
|
|
1506
|
+
| -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ |
|
|
1507
|
+
| JSON nesting | 128 values | `INVALID_DOCUMENT` |
|
|
1508
|
+
| React markup nesting, attributes per element | `maxDepth` + 4 levels (at most 256), 32 attributes | `LIMIT_EXCEEDED` |
|
|
1509
|
+
| Table columns, cell spans | 1,000 columns per table; `colSpan` 1–1,000, `rowSpan` 1–65,534 | `LIMIT_EXCEEDED`; spans `INVALID_DOCUMENT` |
|
|
1510
|
+
| SVG structure | 256 levels of elements, `<use>` copies and gradient references, 16 levels of clip paths, and no reference cycles | Cycles use `UNSUPPORTED_IMAGE`. Other bounds use `LIMIT_EXCEEDED`. |
|
|
1511
|
+
| SVG expansion | 1,000,000 expanded elements and 1,000,000 path segments and dash entries. An arc emits at most four cubic segments. | `LIMIT_EXCEEDED` |
|
|
1512
|
+
| SVG CSS | 4 MiB of stylesheet text and fixed budgets for selector work and cascaded declarations | `LIMIT_EXCEEDED` |
|
|
1513
|
+
| Letterhead PDF structure | 128 object levels, 32 filters per decoded stream and 64 MiB per predictor row | `LIMIT_EXCEEDED` |
|
|
1514
|
+
| Attachment names | 255 bytes; no `/`, `\`, `:`, control or bidirectional control characters; not `.` or `..` | `INVALID_DOCUMENT` |
|
|
1515
|
+
| Metadata | `meta.lang` a BCP 47 tag; no control characters in text fields | `INVALID_DOCUMENT` |
|
|
1516
|
+
| Theme CSS (`themeFromCss()`, `theme`) | 4 MiB and 50,000 custom properties per stylesheet, 16 nesting levels, 256 stylesheets, 10,000 JS overrides | `INVALID_THEME` warnings; the rest is ignored |
|
|
1517
|
+
| Theme files (`themeFromCssFile()`) | 64 files, 16 import levels, 256 imports per file, 4 MiB per file, 16 MiB in all; 100 warnings | `INVALID_THEME` warnings; a missing entry file throws |
|
|
1518
|
+
|
|
1519
|
+
The letterhead preflight checks object nesting, cross-reference data, stream expansion and page tree work before opening the PDF. The engine checks each selected page's content before embedding it. It rejects encrypted and unreadable PDFs with `UNSUPPORTED_IMAGE`. Structural limits also apply when the preflight cannot bound an ambiguous object stream, such as a filter defined through an indirect reference.
|
|
1520
|
+
|
|
1521
|
+
The engine never performs network or file I/O: images, fonts, SVGs and PDFs arrive as bytes, SVGs load nothing outside their markup, and links accept only `#id`, `http:`, `https:`, `mailto:` and `tel:`. [SECURITY.md](../SECURITY.md) explains how to report a vulnerability.
|
|
1522
|
+
|
|
1523
|
+
### Not supported yet
|
|
1524
|
+
|
|
1525
|
+
| Area | Not supported in this release |
|
|
1526
|
+
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
1527
|
+
| Text | Inline runs inside a paragraph (mixed styles, inline links, `Span`); vertical text; multi-column text flow; text indent; line clamping; truncation and underline (parsed, rendering planned) |
|
|
1528
|
+
| Typography | Synthetic bold and italic; system fonts; hyphenation of right-to-left text and inside ligatures or cursive and Indic scripts; inter-character justification for Chinese, Japanese and Thai; language-specific CJK font selection; Dutch hyphenation in the npm builds (an optional Rust feature) |
|
|
1529
|
+
| Emoji | COLR and CBDT color fonts are tested; sbix and SVG-in-OpenType fonts are untested |
|
|
1530
|
+
| Graphics | Rounded corners, opacity, dashed and dotted borders (parsed, rendering planned); shadows; transforms (`rotate-*`, `scale-*`); CSS gradients (after 1.0) |
|
|
1531
|
+
| Pages | Page references and tables of contents with page numbers; mirrored margins for odd and even pages; markers on tables and images |
|
|
1532
|
+
| Tables | Custom cell components and element rows inside data tables; header associations for irregular tables (`Headers`) |
|
|
1533
|
+
| Standards | PDF/A-1, PDF/A-4, PDF/A-2a/3a, PDF/UA-2; letterheads in PDF/A and PDF/UA documents; PDF/A files as attachments in PDF/A-2 |
|
|
1534
|
+
| Accessibility | Inline structure (`Em`, `Strong`, links inside a paragraph); `Note`, `Reference`, `TOC`, `Formula`; list numbering detection |
|
|
1535
|
+
| PDF features | Forms, encryption, digital signatures, annotations, merging other PDFs (only letterhead pages) |
|
|
1536
|
+
| Output | Streaming pages while they are rendered (`renderToStream()` writes the whole document first) |
|
|
1537
|
+
| Runtimes | Cloudflare Workers and edge runtimes; Deno (untested); bundler integration for browser builds; React documents in the worker engine |
|
|
1538
|
+
|
|
1539
|
+
See the [1.1.0 milestone](https://github.com/RentnerKev/RentnerPDF/milestone/1) for planned follow-ups.
|
|
1540
|
+
|
|
1541
|
+
## Performance
|
|
1542
|
+
|
|
1543
|
+
- **Reuse one engine** per process. It keeps fonts, parsed class strings (up to 8,192 distinct strings), shaped text runs and decoded images between renders, and owns the threads. Creating an engine per request repeats that work.
|
|
1544
|
+
- **Render many documents with `renderMany()`** on the native backend. The engine renders `threads` documents at once (one per core by default) and shapes the paragraphs of a large document in parallel; parallel `render()` calls share the same threads, so a busy server never oversubscribes its cores. `engine.stats()` shows the renders in progress and waiting, and the cache hits:
|
|
1545
|
+
|
|
1546
|
+
<!-- snippet: web/src/tests/docs/usage/performance.tsx#batch -->
|
|
1547
|
+
|
|
1548
|
+
```tsx
|
|
1549
|
+
import { createEngine } from '@rentnerkev/pdf'
|
|
1550
|
+
|
|
1551
|
+
const engine = await createEngine() // once per process, not per request
|
|
1552
|
+
|
|
1553
|
+
// renderMany keeps the engine's threads busy and memory bounded; with
|
|
1554
|
+
// stopOnError the first failure ends the batch, so every result rendered.
|
|
1555
|
+
const pdfs: Uint8Array[] = []
|
|
1556
|
+
for await (const { pdf } of engine.renderMany(
|
|
1557
|
+
customers.map((customer) => <Statement customer={customer} />),
|
|
1558
|
+
{ stopOnError: true },
|
|
1559
|
+
)) {
|
|
1560
|
+
pdfs.push(pdf)
|
|
1561
|
+
}
|
|
1562
|
+
```
|
|
1563
|
+
|
|
1564
|
+
- **Large tables:** use `<Table data columns>` instead of thousands of `Row`/`Cell` elements, on both JSX paths.
|
|
1565
|
+
- **Images:** pass the same buffer for a repeated logo; the cache (`cache.imageBytesMax`) decodes it once per engine.
|
|
1566
|
+
- **React:** `NODE_ENV=production`; load data with `use()` before or during the render, not in effects. The own runtime adds less to a render than React (S14 in the [benchmarks](../benchmarks/README.md)).
|
|
1567
|
+
- **Repeated texts:** labels and table values that repeat are shaped once per engine (`cache.shapedRunsMax`); the gain is small, as shaping is a small part of a render.
|
|
1568
|
+
- **WebAssembly** blocks its thread while rendering; in browsers, render in a Web Worker ([browser preview](#browser-preview)).
|
|
1569
|
+
|
|
1570
|
+
The [benchmark report](benchmarks.md) records the inputs, runners and results for the published measurements.
|
|
1571
|
+
|
|
1572
|
+
## Playground
|
|
1573
|
+
|
|
1574
|
+
`bun run playground:dev` builds a local web app, serves it on `http://127.0.0.1:4173` and rebuilds it on changes; `bun run playground:build` writes a static build to `web/playground/dist`. It is a JSX editor with examples (invoice, report, data table, factories), a live PDF preview rendered by the WebAssembly engine in a Web Worker (`usePdf` with `createWorkerEngine`), and the render's warnings and wrap diagnostics. It needs `bun run build:wasm` first. It runs locally only.
|
|
1575
|
+
|
|
1576
|
+
The editor holds one module that imports from `@rentnerkev/pdf` (own JSX runtime and factories; not `@rentnerkev/pdf/react` or other packages) and has a default export: a `Document` element, a factory document or a component without props. The local server only transpiles the TSX; the module is evaluated on the page and rendered in the worker, so the editor stays responsive during large renders.
|
|
1577
|
+
|
|
1578
|
+
## Local documentation for tools
|
|
1579
|
+
|
|
1580
|
+
`@rentnerkev/pdf/ai` gives local Node.js and Bun scripts, editors and AI agents read-only access to the installed version: this guide, the README, selected manifest fields and the public TypeScript declarations. It uses `node:fs`, never loads an engine, React or another entry, makes no network requests and needs no MCP runtime. Keep it in tooling code, outside browser bundles.
|
|
1581
|
+
|
|
1582
|
+
<!-- snippet: web/src/tests/docs/usage/ai.ts#ai -->
|
|
1583
|
+
|
|
1584
|
+
```ts
|
|
1585
|
+
import {
|
|
1586
|
+
getPackageApi,
|
|
1587
|
+
getPackageDocumentation,
|
|
1588
|
+
getPackageExamples,
|
|
1589
|
+
getPackageInfo,
|
|
1590
|
+
searchPackageDocumentation,
|
|
1591
|
+
} from '@rentnerkev/pdf/ai'
|
|
1592
|
+
|
|
1593
|
+
console.log(getPackageInfo().version)
|
|
1594
|
+
console.log(getPackageDocumentation('usage').content)
|
|
1595
|
+
console.log(getPackageDocumentation('readme').path)
|
|
1596
|
+
console.log(getPackageApi({ subpath: './react', symbol: 'renderToPdf' }))
|
|
1597
|
+
console.log(searchPackageDocumentation('createEngine'))
|
|
1598
|
+
console.log(getPackageExamples())
|
|
1599
|
+
```
|
|
1600
|
+
|
|
1601
|
+
- `getPackageDocumentation()` defaults to `usage`; only `usage` and `readme` are accepted.
|
|
1602
|
+
- `getPackageApi()` reads the declarations of every public typed entry (`.`, `./react`, `./worker` and the others) and their local dependencies, excluding `/ai`. Optional `subpath` and `symbol` validate a public export; they do not trim the declarations to one symbol. Callers cannot pass file paths.
|
|
1603
|
+
- `searchPackageDocumentation()` is literal and case-insensitive and returns paths, one-based line numbers and the matching lines. `getPackageExamples()` returns the fenced code blocks of this guide as language/code pairs.
|
|
1604
|
+
- Results describe the installed version. The [RentnerPackages website](https://packages.rentner.dev/docs/pdf) serves its documentation snapshot through a read-only MCP server (`https://packages.rentner.dev/mcp`) and [llms.txt](https://packages.rentner.dev/llms.txt); compare its version with yours before you use its examples.
|