# pdfnative-react [![npm version](https://img.shields.io/npm/v/pdfnative-react)](https://www.npmjs.com/package/pdfnative-react) [![CI](https://github.com/Nizoka/pdfnative-react/actions/workflows/ci.yml/badge.svg)](https://github.com/Nizoka/pdfnative-react/actions/workflows/ci.yml) [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE) [![TypeScript](https://img.shields.io/badge/TypeScript-strict-blue)](https://www.typescriptlang.org/) [![pdfnative](https://img.shields.io/badge/pdfnative-1.9-0a7e8c.svg)](https://github.com/Nizoka/pdfnative) [![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/Nizoka/pdfnative-react/badge)](https://scorecard.dev/viewer/?uri=github.com/Nizoka/pdfnative-react) Write PDFs the way you write UIs. **pdfnative-react** turns declarative JSX into real, on-device PDF documents powered by the zero-dependency [`pdfnative`](https://www.npmjs.com/package/pdfnative) engine — no DOM, no headless browser, no SaaS round-trips. Your documents never leave the process. ```tsx import { Document, Heading, Text, Table, renderToBytes } from 'pdfnative-react'; const bytes = renderToBytes( Invoice #1024 Thank you for your business. , ); // → Uint8Array, a valid PDF (%PDF-… …%%EOF) ``` ## Why pdfnative-react - **Declarative & familiar.** 19 components mirror `@react-pdf/renderer` ergonomics (`Document`, `Page`, `Text`, `Image`, `Link`, `usePdf`, `PDFViewer`, `PDFDownloadLink`, `BlobProvider`). - **On-device.** A custom React reconciler compiles your tree — synchronously, with no DOM — to the `pdfnative` model and renders the bytes locally. - **Honest model.** Components map 1:1 onto pdfnative blocks. There is no CSS/flexbox engine and no `` — it is a declarative *block flow*. - **Fine typography.** Paragraphs that split across pages under widow and orphan rules, headings kept with what follows, justification with hanging punctuation, kerning, OpenType features, units and short words that never break — all opt-in. See [Typography](docs/TYPOGRAPHY.md). - **Print colour and PDF/X-4.** CMYK and named spot inks (`/Separation`, `/DeviceN` mixes) on every painted colour position (outline bookmarks stay process RGB, as the PDF specification says), colour bars in the bleed, CMYK and Gray output intents, the PDF/X-4 conformance claim — alone or combined with PDF/A-2 in one file — with every constraint linted before the render. See [Print](docs/PRINT.md). - **Right-to-left and bidirectional text.** `direction="auto" | "rtl" | "ltr"` on the document or per paragraph; Arabic and Hebrew lines wrap from the right under the full UAX #9 algorithm, and every right-to-left run carries its logical text as `/ActualText`, so extraction returns the source string. - **JPEG 2000 images.** A JP2 file or a raw J2K codestream passes straight through as `/JPXDecode` — never decoded, never re-encoded — in `` and in watermarks, with a lint rule for the PDF/A constraints. - **Byte-reproducible.** Pin `creationDate` and the same document renders to the same bytes on every host, in every time zone — proven by the repository on Linux, Windows and macOS. See [Reproducible output](docs/REPRODUCIBLE.md). - **Server-ready.** `renderToResponse` returns a web-standard `Response`, streaming by default — one line in a Next.js route handler, and the same code on Edge, Deno, Bun and Workers. See [Server rendering](docs/SERVER.md). - **Token-frugal AI authoring.** A compact `DocSpec` lets LLM agents emit documents with a fraction of the tokens of JSX, validated by a versioned JSON Schema — see [Agent authoring](#agent-authoring-token-frugal). - **Autonomously usable.** `doctor()`, `capabilityManifest()`, `validateSpec()` and a stable `E_*` error taxonomy let an agent check the environment, discover the API and verify its own output before rendering — see the [agent contract](docs/AGENT_CONTRACT.md). - **Checks its own work.** `lintDocument` reports accessibility problems and pre-empts the engine constraints that would otherwise throw mid-render — 41 lint rules, see [Linting](docs/LINTING.md). - **Validated against veraPDF and `validatePdfX`.** A PDF/A and PDF/X corpus covering both authoring doors is validated with the pinned veraPDF reference validator and the engine's PDF/X validator — locally and as a blocking gate, with negative canaries the validators must reject. See [CONTRIBUTING.md](CONTRIBUTING.md#pdfa-and-pdfx-validation). - **32 Unicode scripts.** Every bundled font module of the engine — Latin with its tone-marked African languages, Arabic, Hebrew, the Indic family down to Gujarati, Gurmukhi, Kannada, Malayalam and Odia, Thai, Lao, Khmer, Myanmar, Tai Tham, Cham, CJK, colour emoji and more — through one `resolveFonts` call, embedded as lean subsets. - **Typed, tested, tree-shakeable.** Strict TypeScript, dual ESM + CJS with per-condition types, source maps, provenance-signed publishes, 949 tests. ## Install ```bash npm install pdfnative-react pdfnative react ``` Requires **React 19**, **`pdfnative` ≥ 1.9**, and **Node.js ≥ 22** (the engine's own floor since 1.6.0). ## Components Every component maps 1:1 onto a pdfnative block. | Component | Renders | |---|---| | `Document` | The required root (`title`, `footerText`, `metadata`, `fontEntries`, `layout`, `outline`, `pageLabels`, `watermark`, `header`, `footer`, `attachments`, `tagged`, `print`, `pdfx`, `outputIntent`, `typography`, `creationDate`, `direction`). | | `Page` | An explicit page boundary (content auto-paginates otherwise). | | `Section` | Sugar: a heading grouped with its content (`title`, `level`, `color`, `break`). | | `Heading` | A section heading (`level` 1–3, `keepWithNext`); feeds the auto `TableOfContents`. | | `Paragraph` / `Text` | A wrapping paragraph (`fontSize`, `lineHeight`, `align` incl. `'justify'`, `indent`, `color`, `keepWithNext`, `splittable`, `direction`). | | `List` / `Item` | A bullet or numbered (`ordered`) list; items may nest sub-lists. | | `Table` / `Row` / `Cell` | A data table (`headers`/`rows` or JSX children; `cellBorders`, `cellVAlign`, `zebra`, `caption`, …). | | `Image` | An embedded JPEG, PNG (no alpha channel — flatten colour types 4 and 6 first) or JPEG 2000 (`data: Uint8Array`; a JP2 file or a J2K codestream passes through as `/JPXDecode`). | | `Link` | A clickable hyperlink (`url`/`href`). | | `Spacer` | Vertical whitespace (`height`). | | `PageBreak` | A hard page break. | | `TableOfContents` / `Toc` | An auto-generated TOC built from headings. | | `Barcode` | QR, Code 128, EAN-13, PDF417, Data Matrix (`format`, `data`). | | `Svg` | Inline vector graphics (path data or markup; `` renders as selectable PDF text). | | `Chart` | Native vector charts — bar, barH, line, pie, donut, stackedBar, stackedBarH, area, scatter; log/time scales, dual axes, data labels, one colour per bar (`series.colors`) ([guide](docs/CHARTS.md)). | | `FormField` | Interactive AcroForm widgets (`fieldType`, `name`). | Every `color` prop — and chart palettes, table borders and zebra stripes, watermarks, headers and footers — accepts a hex string, an RGB tuple, a CMYK tuple in percent (`[0, 60, 100, 0]`), a PDF operator string, or a named ink declared under `print.spotColours`: `{ spot: 'PANTONE 300 C', tint: 0.5 }` (a `/Separation`) or `{ inks: { 'PANTONE 300 C': 1, Varnish: 0.3 } }` (a `/DeviceN` mix). ### Document-level page furniture `watermark`, `header`, `footer`, `attachments`, `tagged`, `print`, `pdfx`, `outputIntent`, `typography`, `creationDate` and `direction` are props on `` rather than components, because they are page furniture, not blocks in the flow. They fold into `layout` under the engine's own keys, and an explicit `layout` prop always wins. ```tsx ``` Header and footer templates resolve `{page}`, `{pages}`, `{date}` and `{title}` at render time (`{date}` follows a pinned `creationDate`). `print` adds bleed/trim/art/crop boxes, vector printer's marks, colour bars and large-format `userUnit`, and declares named inks under `print.spotColours`; `metadata.trapped` and the print-dialog viewer preferences (`duplex`, `printPageRange`, `numCopies`, `pickTrayByPDFSize` under `layout.viewerPreferences`) complete the prepress surface — see [samples/layout/print-production.tsx](samples/layout/print-production.tsx). `tagged` and `pdfx` combine: `tagged="pdfa2b"` or `"pdfa2u"` beside `pdfx="pdfx4"` writes both identifications into one file (PDF/A-1 and PDF/A-3 stay incompatible with PDF/X-4, and `L_PDFX_TAGGED_CONFLICT` says why). `direction` sets the base text direction of every paragraph (`'auto'` detects it from the first strong character; `` overrides it per block); omitted, the output is byte-identical to 1.3. ### Typography ```tsx Results … ``` All twelve keys are off by default: a document that sets none renders byte-identically to earlier releases. `align="justify"` is paragraph-only (`ParagraphAlign = Align | 'justify'`). No hyphenation dictionary ships — soft hyphens (U+00AD) are honoured and `setHyphenationProvider` accepts yours. Anything a font cannot deliver is a lint finding (`L_TYPOGRAPHY_INEFFECTIVE`) before it is an engine diagnostic. Guide: [docs/TYPOGRAPHY.md](docs/TYPOGRAPHY.md). ### Right-to-left text ```tsx const fontEntries = await resolveFonts({ ar: () => import('pdfnative/fonts/noto-arabic-data.js'), he: () => import('pdfnative/fonts/noto-hebrew-data.js'), }); // 'auto' | 'ltr' | 'rtl' {arabicText} // set from the right margin {englishText} // per-block override ``` `direction="auto"` resolves each paragraph's base direction from its first strong character (UAX #9 P2–P3); `'rtl'` and `'ltr'` force it. Digits, brackets and punctuation pair and mirror under the full bidirectional algorithm, and every right-to-left run carries its logical text as an `/ActualText` span, so `extractText` and copy-paste return the source string (`layout.actualText: false` opts out). Omit `direction` and the document renders byte-identically to 1.3. Sample: [samples/text/rtl-direction.tsx](samples/text/rtl-direction.tsx). ### Print colour and PDF/X-4 ```tsx Press sheet Set in DeviceCMYK. ``` `pdfx="pdfx4"` writes the PDF/X-4 identification, a `/GTS_PDFX` output intent, a TrimBox per page and `/Trapped`. Every constraint the engine enforces — an output intent with a printer profile, a known trapping state, embedded fonts, no PDF/A-1 or PDF/A-3 claim beside it, no encryption, a TrimBox *or* an ArtBox — is an `L_PDFX_*` lint rule before it is a throw. Check the bytes with the engine's `validatePdfX()` ([recipe](docs/RECIPES.md#validate--and-see--the-output)); a `valid` result means the structural prerequisites hold, not that a certified preflight passed. Guide: [docs/PRINT.md](docs/PRINT.md). **Spot colours.** Declare the press inks once under `print.spotColours`, then paint with them anywhere a colour goes — headings, paragraphs, links, table borders and zebra stripes, chart palettes, watermarks, headers and footers: ```tsx One plate of its own A 50 % tint — a /Separation space. An ink mix — a /DeviceN space. ``` An ink that is not declared is `L_SPOT_UNDECLARED`, a mix across alternate spaces (CMYK beside RGB) is `L_SPOT_INK_MIX`, a bad declaration is `L_PRINT_BOXES` — each before the engine's own throw, which arrives as `E_INPUT` when the linter is skipped. Sample: [samples/layout/print-spot-colours.tsx](samples/layout/print-spot-colours.tsx). **PDF/A-2 and PDF/X-4 in one file.** `tagged="pdfa2b"` (or `"pdfa2u"`) combines with `pdfx="pdfx4"`: the file carries both XMP identifications and passes veraPDF and `validatePdfX` alike. PDF/A-1 (PDF 1.4) and PDF/A-3 (embedded files) remain incompatible with PDF/X-4, which is what `L_PDFX_TAGGED_CONFLICT` now fires on. Sample: [samples/layout/print-dual-pdfa2b-pdfx4.tsx](samples/layout/print-dual-pdfa2b-pdfx4.tsx). ### Reproducible output ```tsx // this document setDefaultCreationDate(new Date('2026-01-01T00:00:00Z')); // every document in this process ``` Every date the engine writes is UTC; the `{date}` placeholder and the trailer `/ID` follow the pin; the same document gives the same bytes on every host. The library reads no environment variable — a pipeline exporting `SOURCE_DATE_EPOCH` applies it in one line of its own. Encrypted output is not reproducible by design. `renderToResponse({ etag: true })` is therefore a stable validator only when the document is pinned. Guide: [docs/REPRODUCIBLE.md](docs/REPRODUCIBLE.md). ## Rendering ```ts import { renderToBytes, // (node, options?) => Uint8Array renderToBlob, // (node, options?) => Blob (application/pdf) renderToStream, // (node, options?) => AsyncGenerator (constant memory) renderToFile, // (node, path, options?) => Promise (Node only) renderToFileStream, // (node, path, options?) => Promise (Node, constant memory) renderToResponse, // (node, options?) => Promise (streams; web standard) compileDocument, // (node) => DocumentParams (inspect the model, no render) inspectDocument, // (node, options?) => LayoutInspection (page/block geometry, no render) lintDocument, // (node, options?) => LintReport (accessibility + engine constraints) } from 'pdfnative-react'; ``` ### Serving a PDF ```tsx // app/invoice/[id]/route.tsx — Next.js App Router export async function GET() { return renderToResponse(, { fileName: 'invoice.pdf' }); } ``` Streams page by page, so peak memory stays flat and the client receives bytes immediately. `buffered: true` switches to a single buffer and adds `Content-Length`. Works unchanged on Node, Edge, Deno, Bun and Cloudflare Workers — see [docs/SERVER.md](docs/SERVER.md). `options` is `{ layout?: Partial; fontEntries?: FontEntry[]; fonts?: FontsMap }` and merges on top of anything set on `` — page size, margins, colors, PDF/A mode, encryption, viewer preferences, typography, debug overlay, and non-Latin fonts. `renderToFileStream` writes page by page with constant memory and preserves document-level features (outline, page labels). The `fonts` loader map is honored only by the async entry points (`renderToFile`, `renderToFileStream`, `renderToResponse`, `usePdf`, `usePdfStream`); for the synchronous entries resolve it first with `fontEntries: await resolveFonts({ … })`. ### Bookmarks, page labels & viewer preferences ```tsx … ``` `outline` builds the reader's bookmark sidebar (`'auto'` derives it from your headings, or pass a nested `OutlineItem[]`). `layout.viewerPreferences` controls how a viewer opens the document. All PDF/A-safe. ### Layout debugging `layout.debug` overlays margin/content/cell boxes onto the PDF, and `inspectDocument(node)` returns the same geometry as data (page count, and each block's position/size) without rendering — handy for tests and tooling, and the cheapest way to see where a paragraph split. ### Nested lists ```tsx FruitsApplePear Vegetables ``` Sub-lists nest as a child ``, as directly nested `` children, or via the `items` data prop (`{ text, items }`). Nested lists inherit the parent style. ## Hooks & client components These run in the browser. In a React Server Components app, import them from the **`pdfnative-react/client`** subpath, which ships with `'use client'` already applied — no wrapper file needed. The root barrel exports them too, for apps without an RSC boundary. ```tsx import { usePdf } from 'pdfnative-react/client'; function Preview({ doc }: { doc: React.ReactElement }) { const { url, loading } = usePdf(doc); return loading ?

Rendering…

: