Skip to content
Inkoxide

Search covers every page and heading of the docs. Use ↑ ↓ and ↵.

In the browser

Edit this page

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 until update(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. options are those of renderToBuffer below, read when a render starts.
  • <PdfDownloadLink> is a link that downloads the PDF: document, fileName (default 'document.pdf'), options and the props of an <a>; its children may be a function of the usePdf result. <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 (false adds #toolbar=0 to the URL, which Chromium's viewer follows), title (default 'PDF') and the props of an <iframe>. <BlobProvider> shows what its function child makes of the usePdf result: <BlobProvider document={doc}>{({ url }) => …}</BlobProvider>. Each renders when it mounts and again when document changes: an element of another type or key, or one whose props are not the same values (<Invoice invoice={invoice} /> made again with the same invoice is 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 are PdfDownloadLinkProps, PdfViewerProps and BlobProviderProps.
  • renderToBuffer, renderToBlob and renderToStream render outside React components, and generate renders a template. Their options (BrowserRenderOptions, and GenerateOptions for generate) are those of the Node entry, with a signal or timeoutMs (a time in ms) that stops a render: its worker ends, and the next render starts a new one. timeoutMs counts the whole render, the loading of its images and every pass; 0 has passed already, so the render always stops. A render that times out rejects with a DOMException named TimeoutError. renderToStream returns a promise of a web ReadableStream<Uint8Array> of the PDF in 64 KiB chunks: pass it to a Response (in a service worker, say), or write it to a file the user picked, with (await renderToStream(<Invoice />)).pipeTo(await handle.createWritable()) for a handle from showSaveFilePicker(). 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 with INTERNAL, and the next one starts it again, with its own options. The options (BrowserOptions): wasm is where the module comes from (a URL, a Response, its bytes or a compiled WebAssembly.Module, of either module); assets is a folder to serve the bundled fonts and hyphenation patterns from: fonts/ and hyphenation/ from @inkoxide/react's assets/, with the .bin files of @inkoxide/wasm's hyphenation/ in hyphenation/ too; threads is how many threads renders use (below); worker: false renders 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 threads may only be 1, and with one, any larger number uses the whole pool.
  • renderToFile and 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.