In the browser
The same templates render in a browser, with the engine as WebAssembly in a Web Worker, so the
page keeps responding while it renders. Install the module next to the package, and import
from @inkoxide/react/browser:
npm install @inkoxide/react @inkoxide/wasm
import { PdfDownloadLink, PdfViewer, usePdf } from '@inkoxide/react/browser';
function InvoicePage({ invoice }: { invoice: InvoiceData }) {
const doc = <Invoice invoice={invoice} />;
return (
<>
<PdfDownloadLink document={doc} fileName="invoice.pdf">
{({ loading }) => (loading ? 'Rendering…' : 'Download')}
</PdfDownloadLink>
<PdfViewer document={doc} style={{ width: '100%', height: 800 }} />
</>
);
}
usePdf(element?, options?)renders when the component mounts and returns{ blob, url, loading, error, update }(UsePdfResult);update(element?)renders again. Without an element nothing renders untilupdate(element). A render that starts stops the one still running, and the object URL is revoked when a new one replaces it and on unmount.optionsare those ofrenderToBufferbelow, read when a render starts.<PdfDownloadLink>is a link that downloads the PDF:document,fileName(default'document.pdf'),optionsand the props of an<a>; its children may be a function of theusePdfresult.<PdfViewer>is an<iframe>with the browser's own viewer:document,options,fallback(shown until the first render has finished, and when it failed),showToolbar(falseadds#toolbar=0to the URL, which Chromium's viewer follows),title(default'PDF') and the props of an<iframe>.<BlobProvider>shows what its function child makes of theusePdfresult:<BlobProvider document={doc}>{({ url }) => …}</BlobProvider>. Each renders when it mounts and again whendocumentchanges: an element of another type or key, or one whose props are not the same values (<Invoice invoice={invoice} />made again with the sameinvoiceis the same document). A render that starts stops the one still running, and the last PDF stays until the next one is ready. Their props arePdfDownloadLinkProps,PdfViewerPropsandBlobProviderProps.renderToBuffer,renderToBlobandrenderToStreamrender outside React components, andgeneraterenders a template. Their options (BrowserRenderOptions, andGenerateOptionsforgenerate) are those of the Node entry, with asignalortimeoutMs(a time in ms) that stops a render: its worker ends, and the next render starts a new one.timeoutMscounts the whole render, the loading of its images and every pass;0has passed already, so the render always stops. A render that times out rejects with aDOMExceptionnamedTimeoutError.renderToStreamreturns a promise of a webReadableStream<Uint8Array>of the PDF in 64 KiB chunks: pass it to aResponse(in a service worker, say), or write it to a file the user picked, with(await renderToStream(<Invoice />)).pipeTo(await handle.createWritable())for ahandlefromshowSaveFilePicker(). As in Node, the stream starts once the PDF is ready, and a failed render rejects the promise.init(options?)starts the engine, and every render calls it; only the options of the first call count. When the engine cannot start (the module did not download, say), the call rejects withINTERNAL, and the next one starts it again, with its own options. The options (BrowserOptions):wasmis where the module comes from (a URL, aResponse, its bytes or a compiledWebAssembly.Module, of either module);assetsis a folder to serve the bundled fonts and hyphenation patterns from:fonts/andhyphenation/from@inkoxide/react'sassets/, with the.binfiles of@inkoxide/wasm'shyphenation/inhyphenation/too;threadsis how many threads renders use (below);worker: falserenders on the calling thread.clearCaches()empties the engine's caches of decoded images, font subsets and SVG text. The memory stays with the engine, which reuses it for the next renders; the PDFs are the same.
Setting up. Bundlers copy the module, the worker and the bundled fonts, which the packages
refer to with new URL(…, import.meta.url). With Vite, set worker: { format: 'es' } for the
engine's module worker. For the dev server, also add
optimizeDeps: { exclude: ['@inkoxide/wasm'] }: pre-bundling moves the module away from its
hyphenation/ folder, and a document that hyphenates a language other than English then fails
with INTERNAL (engineCode NOT_LOADED). examples/browser
is a Vite page; its vite.config.ts sets worker.format, the policy below, and an alias that
points @inkoxide/react at @inkoxide/react/browser, so that components written for Node
import unchanged. To use the engine without React, with document trees as JSON, see
@inkoxide/wasm.
Fonts and images. A bundled font is downloaded the first time a document uses it, as a
TrueType file, for the same PDF as on the server. Font.register takes a URL (relative to the
page), the bytes or a Blob; a file path (a file: URL, a drive letter or a backslash) fails
the render with INVALID_FONT. A WOFF2 font gives other PDF bytes than its TrueType file;
WOFF gives the same. Images come as bytes in images, as a Blob (a File from
<input type="file"> or a drop) in <Image src>, or from the hosts allowed in remoteImages:
the requests carry no cookies, need CORS, and a redirect is refused. localImages is not
available.
Content Security Policy. The engine needs script-src 'wasm-unsafe-eval' and a worker of
the page's origin (worker-src 'self'). <PdfViewer> shows the PDF from an object URL
(blob:), as does a frame or an image given usePdf().url: allow it with frame-src blob:, and
img-src blob: for an image. The policy of examples/browser allows both. Nothing needs 'unsafe-eval', and the page needs no
cross-origin isolation (COOP and COEP), unless it wants threads.
From a CDN. A page cannot start a worker from a script of another origin. When
@inkoxide/react and @inkoxide/wasm are served from one (a CDN), the engine's worker, and
the pool's threads, start as a worker of the page's origin from a blob: URL that imports the
script. The CDN must serve the scripts and assets with CORS (Access-Control-Allow-Origin), and
the policy needs worker-src blob:, with script-src and connect-src allowing the CDN. On a
page that is cross-origin isolated, the CDN's files also need CORS or Cross-Origin-Resource-Policy: cross-origin. Scripts of the page's own origin start workers as before, and worker-src 'self'
is enough. Bundlers still see new Worker(new URL(…, import.meta.url)).
Threads in the browser
On a page that is cross-origin isolated, the engine renders on a pool of threads, as on the server: shaping, painting and compression run on several cores. Serve the page with
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp
on every response, a 304 Not Modified included: WebKit refuses to start the engine's worker
again from its cache when a 304 lacks them. threads (default 'auto') is then the number of
cores, at most 8; 1 keeps one thread, and a number asks for that many (up to 256). The engine
downloads its module with threads instead of the other, starts that many more workers, which
share its memory, and engineStatus().threads tells how many it got. Without isolation, with
worker: false, or where the browser cannot reserve the module's memory (at most 2 GiB), it
renders on one thread. The PDFs are the same bytes either way.
A long document gains most: the engine alone renders a 98-page report about 2.2 times as fast on
4 threads and 2.9 times on 8 (measured in Node). A React document gains less, since its tree is
built in JavaScript, on one thread: 1.3 times for the 43-page report of the benchmarks, on 4
threads as on 8; a one-page invoice gains nothing. Give renders a timeoutMs with threads: a
bug on a pool thread that cannot reach the page leaves its render waiting. Isolation
also blocks resources from other origins that do not allow it (CORS, or a
Cross-Origin-Resource-Policy header), such as images, fonts and embeds. A bug in the engine on
one of its threads ends the worker, as signal does, and the render fails with INTERNAL.
Where the pool's workers cannot start (a worker-src policy, or a bundler that does not copy the
engine's nested worker), the engine renders on one thread.
What differs from Node.
- Renders run in one worker, one at a time, on one thread unless the page is cross-origin
isolated (threads); without a pool
threadsmay only be1, and with one, any larger number uses the whole pool. renderToFileand image files are not available.- The engine module is about 1.4 MB to download with brotli, once, and Tailwind's compiler
about 90 KB when templates use
className, or a few KB with the build plugin. A bundled font (65 to 245 KB with brotli) is downloaded when a document first draws with it: Noto Sans, the fallback, only for a character Inter lacks. The English hyphenation patterns (34 KB) are downloaded when the engine starts, and another language's (1 to 350 KB) when a document first hyphenates text in it. - The PDF has the bytes Node renders, except where SVG markers are rotated and where SVG text follows a path: their numbers can differ in the last digits, since the browser's math library rounds differently.
- A bug in the engine fails the render with
INTERNAL; the next render runs in a new instance.
Synced from packages/react/GUIDE.md in the inkoxide repository.