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-exporterThen, 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
titleandlangin the export options.langis 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. Noto Color Emoji remains the fallback when you supply
custom fonts. Omit emojiFont to keep it. To replace it, supply your
own emoji font file and set emojiFontFamily to the family name in that
file. To disable the emoji fallback, set emojiFont: [] and
emojiFontFamily: undefined. Set fonts: [] to skip the bundled body,
code, and math fonts.
const exporter = new PDFExporter(editor.schema, typstDefaultSchemaMappings, {
fontFamily: "My Font",
monoFontFamily: "My Mono Font",
fonts: [myFontBlob, myMonoFontBlob],
});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), so you can replace the offending file before
retrying. 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. If you only have webfonts and
know which ones you need before deployment, decode them once at build
time. Then pass the unpacked files to the exporters for embedding. This
saves each browser from repeating the conversion. Use static .ttf files
for fonts shared across PDF, DOCX, and ODT, and check that the font license
allows unpacking and embedding.
On Node.js 22.12 or later, 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. Unpacking preserves the outlines: the result is .ttf or .otf.
PDF accepts either; DOCX and ODT embedding require static TrueType.
For fonts selected at runtime, such as a user upload, the same opt-in
helper runs in the browser. It detects the format from the bytes and
accepts a Blob (including File), ArrayBuffer, or Uint8Array:
import { decodeWebFont } from "@blocknote/xl-pdf-exporter/font";
const result = await decodeWebFont(uploadedFile);
if (result.error !== undefined) {
throw new Error(`Could not unpack the font: ${result.error}`);
}
// Pass result.bytes to the exporter's fonts option.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+ on the server. If your
browser's Content Security Policy blocks WebAssembly or runtime JavaScript
generation, WOFF2 decoding returns unsupported-runtime. Use the build-time
approach for known fonts in that case. The helper limits both input and
unpacked output to 30 MiB.
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.