BlockNote DocsFeaturesExportPDF

PDF Export

It's possible to export BlockNote documents to PDF, completely client-side. The exporter is powered by the Typst typesetting engine (compiled to WebAssembly) and produces accessible, tagged documents; see PDF/UA conformance.

This feature is provided by the @blocknote/xl-pdf-exporter. xl- packages are fully open source, but released under a copyleft license. A commercial license for usage in closed source, proprietary products comes as part of the Business subscription.

First, install the @blocknote/xl-pdf-exporter package:

npm install @blocknote/xl-pdf-exporter

Then, create an instance of the PDFExporter class and export the document:

import {
  PDFExporter,
  typstDefaultSchemaMappings,
} from "@blocknote/xl-pdf-exporter";

// Create the exporter
const exporter = new PDFExporter(editor.schema, typstDefaultSchemaMappings);

// Export the document; the result carries the PDF as bytes and as a Blob
const result = await exporter.toPDF(editor.document, {
  title: "My document",
  lang: "en",
});
if (!result.error) {
  const url = URL.createObjectURL(result.blob);
  // e.g. open or download `url`
}

This works out of the box, fully offline: exports match the editor's look, and everything needed (the default fonts and the compiler itself) ships inside the package. Nothing is fetched from a CDN.

See the full example with a live PDF preview below:

Customizing the PDF

toPDF takes per-export options: the document metadata and page setup.

const result = await exporter.toPDF(editor.document, {
  // Document title, shown in the viewer's title bar
  title: "My document",
  // Document author, written to the PDF metadata
  author: "John Doe",
  // BCP-47 language tag of the document's natural language
  lang: "en",
  // Typst paper name, e.g. "a4" (default) or "us-letter"
  paper: "a4",
  // Page margin as a Typst length
  margin: "48pt",
  // Raw Typst markup for the running page header / footer, e.g. a
  // page counter: "#context counter(page).display()"
  header: "My document",
  footer: "#context counter(page).display()",
});

The remaining export options are tryDeclarePdfUA, assets (extra files for caller-supplied header/footer markup), and creationTimestamp (a fixed Unix timestamp for byte-reproducible output).

A document that fails to compile (e.g. text in a script the loaded fonts don't cover) is reported in the result as { error: "compile-failed" } with the compiler's diagnostics, rather than thrown.

PDF/UA conformance

The produced PDF is always tagged: it carries a logical structure tree (headings, paragraphs, lists, tables, figures with alt text, links) that screen readers can navigate. On top of that, the exporter declares PDF/UA-1 conformance when, and only when, the document earns it: Typst validates conformance during the compile, and a nonconforming document is exported as tagged-but-unclaimed instead, with the violations reported in the result:

const result = await exporter.toPDF(editor.document, {
  title: "My document",
  lang: "en",
});
if (
  !result.error &&
  !result.pdfUA.declared &&
  result.pdfUA.reason === "nonconforming"
) {
  // e.g. "PDF/UA-1 error: the first heading must be of level 1"
  console.info(result.pdfUA.violations.map((v) => v.message));
}

What conformance requires of the document:

  • Title and language: pass title and lang in the export options. lang is required to attempt the claim at all: a wrong language declaration is an accessibility defect no validator can catch, so exporting without it throws.
  • Headings: the first heading must be level 1, and levels must be consecutive (no jumping from H1 to H3).

Images always get the alt text PDF/UA requires, derived from the caption with the file name as fallback. Captions make far better alt text, so encourage them.

Pass tryDeclarePdfUA: false in the export options to skip the validation and claim entirely, e.g. for a live preview, where the validation compile would be wasted work. For live previews, also create a fresh exporter per export, since an instance accumulates the image assets it resolves.

Custom mappings / custom schemas

The PDFExporter constructor takes a schema and mappings parameter. A mapping converts a BlockNote schema element into a Typst markup string, and the mappings are shared with the standalone Typst export. See custom mappings there; everything on writing them applies to this exporter unchanged.

Math & diagram blocks

The math and diagram blocks ship their own Typst mappings: math exports as native Typst equations (real text, not images), diagrams as embedded vector graphics. See exporting math and exporting diagrams for the setup.

Fonts

PDF exports bundle Inter 18pt (body), Geist Mono (code), New Computer Modern Math, and Noto Color Emoji. Set fonts to replace the body, code, and math fonts, and emojiFont to replace the emoji font independently. Omit either option to keep its defaults, or pass [] to load none.

const exporter = new PDFExporter(editor.schema, typstDefaultSchemaMappings, {
  fontFamily: "My Font",
  monoFontFamily: "My Mono Font",
  fonts: [myFontBlob, myMonoFontBlob],
  emojiFont: myEmojiFontBlob,
});

Use the family names declared in the files. Typst reports unknown names in compileWarnings. Pass TTF, OTF, or TTC files as Blob (including File), ArrayBuffer, or Uint8Array. Unsupported or unreadable files produce a compileErrors entry with the file's position in the body or emoji list (starting at 1). If you only have WOFF or WOFF2 files, see Unpacking webfonts.

To add a fallback font alongside the defaults, use loadDefaultBodyFonts():

import {
  DEFAULT_FONT_FAMILY,
  loadDefaultBodyFonts,
  PDFExporter,
  typstDefaultSchemaMappings,
} from "@blocknote/xl-pdf-exporter";

const exporter = new PDFExporter(editor.schema, typstDefaultSchemaMappings, {
  fontFamily: [DEFAULT_FONT_FAMILY, "Noto Sans SC"],
  fonts: loadDefaultBodyFonts().then((fonts) => [...fonts, notoSansSCBytes]),
});

Unpacking webfonts

Use the original desktop font if available, and check that its license allows unpacking and embedding. For webfonts selected at runtime, decodeWebFont detects WOFF and WOFF2 from the file bytes. It accepts a Blob (including File), ArrayBuffer, or Uint8Array:

import { decodeWebFont } from "@blocknote/xl-pdf-exporter/font";

const response = await fetch("/fonts/MyFont.woff2");
if (!response.ok) throw new Error("Could not fetch the font");

const result = await decodeWebFont(await response.blob());
if (result.error !== undefined) {
  throw new Error(`Could not unpack the font: ${result.error}`);
}
// Pass result.bytes to the exporter's fonts option.

On success, the result includes bytes and extension ("ttf" or "otf"). Unpacking preserves the outlines: PDF accepts either output, while DOCX and ODT embedding require static TrueType.

WOFF uses the runtime's DecompressionStream API (Chrome 80+, Firefox 113+, Safari 16.4+, or Node.js 18+). WOFF2 loads a WebAssembly decoder on demand and requires Node.js 22.12+ when used on a server. If your browser's Content Security Policy blocks WebAssembly or runtime JavaScript generation, WOFF2 decoding returns unsupported-runtime. Use the build step below in that case. The helper limits both input and unpacked output to 30 MiB.

If the font is known before deployment, use the same helper in a build step so your app can load the unpacked font directly. Save this script as unpack-font.mjs and run node unpack-font.mjs Font-Regular.woff2:

import { readFile, writeFile } from "node:fs/promises";
import { decodeWebFont } from "@blocknote/xl-pdf-exporter/font";

const source = process.argv[2];
const result = await decodeWebFont(await readFile(source));
if (result.error !== undefined) {
  throw new Error(`Could not unpack ${source}: ${result.error}`);
}
await writeFile(
  `${source.replace(/\.woff2?$/i, "")}.${result.extension}`,
  result.bytes,
);

The script accepts either .woff or .woff2. Repeat for each face you need and pass the resulting files to the exporter.

Self-hosting the compiler

The Typst compiler is a ~25MB wasm file from @blocknote/xl-typst-compiler, by default emitted as an asset by your bundler. To control where it is served from (e.g. with caching headers), pass its URL or bytes:

import compilerWasmUrl from "@blocknote/xl-typst-compiler/wasm?url";

const exporter = new PDFExporter(editor.schema, typstDefaultSchemaMappings, {
  wasm: compilerWasmUrl,
});

Exporter options

The PDFExporter constructor takes an optional third options parameter:

const defaultOptions = {
  // a function to resolve external resources (e.g. images) in order to avoid
  // CORS issues; by default, this calls a BlockNote hosted server-side proxy
  resolveFileUrl: corsProxyResolveFileUrl,
  // the strings rendered into the exported document (file link texts, error
  // placeholders); pass a locale from @blocknote/core/locales (or your
  // editor's dictionary) to export in another language
  dictionary: locales.en,
  // the colors used for highlighting, background colors and font colors
  colors: COLORS_DEFAULT, // defaults from @blocknote/core
  // font families; omit fonts and emojiFont to use the bundled files
  fontFamily: "Inter 18pt",
  monoFontFamily: "Geist Mono",
  // base font size in points
  fontSize: 12,
  // where the compiler wasm loads from - see "Self-hosting the compiler"
  wasm: undefined, // the packaged wasm
};

Exporting Typst markup

The underlying Typst source export is available standalone (e.g. to compile with your own Typst toolchain, including server-side); see Typst export.

Deprecated: the react-pdf exporter

Previous versions of @blocknote/xl-pdf-exporter exported PDFs with react-pdf, producing untagged (not accessible) documents. That exporter is deprecated and will be removed after a few releases; until then it remains available unchanged from the @blocknote/xl-pdf-exporter/react-pdf subpath:

import {
  PDFExporter,
  pdfDefaultSchemaMappings,
} from "@blocknote/xl-pdf-exporter/react-pdf";

Note that its mappings are react-pdf mappings; when migrating to the new exporter, custom blocks need a Typst mapping instead. The old exporter's example lives on at converting-blocks-to-pdf-react-pdf-deprecated.