Exports: PDF, DOCX, HTML and source
Export a rendered document as a PDF, an editable Word file, a standalone HTML file or its Typst source, in the browser or on the server, and handle export errors.
A document on screen can be saved four ways: as a PDF, as an editable Word file (DOCX), as an HTML file that opens on its own, or as its Typst source. Exports run in the same engine that renders the preview, so the file matches what the reader sees, and they don't need a second download or a server.
Where the exports are
| DOCX (beta) | HTML | Source | ||
|---|---|---|---|---|
EngineDocument (@typstream/engine) | exportPdf(options?) | exportDocx(options?) | exportHtml(options?): Typst's raw HTML | exportSource() |
MountedTypstream (@typstream/dom) | exportPdf(options?) | exportDocx(options?) | exportHtml(options?): a standalone file | exportSource() |
React (typstream, @typstream/react) | exportPdf(options?) | exportDocx(options?) | exportHtml(options?): a standalone file | exportSource() |
In React, the exports are on useTypstream() (t.exportPdf()) and on the handle <Typstream ref> gives you. They
are MountedTypstream's: the component mounts one. Documents open when their element comes near the viewport, or when
they start streaming; an export opens one that hasn't opened yet. Before the <Typstream> mounts, and after it
unmounts, the exports reject (exportSource() throws) with "<Typstream> isn't mounted".
What an export compiles
An export compiles exportSource(): the healed input, with lint fixes applied. It compiles it in final mode (strictly,
as a finished document) with the document's preamble and files, in the engine's worker.
- Export the finished document. While the document is still streaming, the healed source includes tail repair:
whatever the stream cut left open, closed. Export after streaming ends (
isStreamingback to false, orfinish()on anEngineDocument). - Exports go first. An export runs before compiles that are waiting, so a busy preview doesn't hold it up.
- Budget. An export has the final watchdog budget, 10 seconds by default (
createEngine({ watchdog: { finalMs } })). Past it, the worker is replaced and the export fails withtimeout. - Packages and fonts. An export waits up to 3 seconds for packages the document imports and for fonts its compile lacked, then compiles with what has arrived.
Inputs
exportPdf, exportDocx and exportHtml take { inputs }, sys.inputs for that export only. Use them when the export should
differ from the preview: a teacher's copy ({ showAnswers: "true" }, see
edu documents), or a student's copy
({ showAnswers: "false" }) while the preview shows answers.
- React and
MountedTypstreamcompile with the template's inputs and theinputsprop or option, then the export'sinputsover them. They leave out the inputs oflayout="reflow", which lays pages out at the element's width, so the export comes out at the document's own page size. EngineDocumentcompiles with the document's current inputs, or with exactly the export'sinputswhen you give them: they replace the document's rather than adding to them. A mounted document's inputs include reflow's page size, so in React and withmountTypstream, export through the component or the mount, notdocument.
const pdf: Uint8Array = await doc.exportPdf();It is Typst's own PDF export, with selectable text and the fonts embedded.
DOCX
const docx: Uint8Array = await doc.exportDocx();An editable Word file that lays out as the PDF does: the same lines on the same pages. It is read from the same laid-out pages as the PDF, and written as Word's own structure, so a teacher can edit it:
- paragraphs and their runs (fonts, sizes, colours, links), headings with Word's heading styles, lists with Word's
numbering, tables and grids with Typst's column widths and repeated header rows, framed boxes as one-cell tables,
ruled lines,
columnsas Word's columns, placed text as frames where Typst put it; - page size and margins, headers and footers, page numbers as fields (numbered as Typst numbers the pages: roman numerals for front matter and a restart, as Word sections), page breaks where Typst starts a page, outlines with Word's dot leaders;
- equations as Word equations you can edit: fractions, scripts and limits, roots, brackets, matrices and
cases, big operators with their operands, function names, accents, braces and aligned lines, inline in their line or displayed (a numbered one with its number at the right), in Typst's math font; - what Word can't draw as pictures, at the size and place Typst drew them: images, CeTZ and fletcher canvases, mind
maps, edu's number lines, graph paper and coordinate planes (with their descriptions as alt text), and
placed drawings anchored to the page. Each is Typst's own drawing as SVG, which Word 2016 and later, LibreOffice and ONLYOFFICE draw, with a 300 DPI PNG for older Word and other apps; - Typst's fonts, embedded, so Word sets the text in the faces the PDF uses, and text in every script: Arabic and Hebrew right to left (right-to-left paragraphs, with their lists and tables mirrored as Typst mirrors them), Bengali and Devanagari as written, each run with its language;
- the layout profile's settings, which make Word break lines and pages where Typst does: exact line pitch, ragged right, no hyphenation, rows that stay on one page.
Free-form drawing that Word could keep editable if it were drawn otherwise, a box with rounded corners, filled with a
gradient or rotated text, becomes a picture too, its text with it, and the export warns about it: a diagnostic with
code: "docx/fallback" at the box. edu's callout draws a box Word keeps editable, and heal's
layout-profile lint rule squares the corners of the boxes a model draws around
text, on the page too, so they come out as table cells Word can edit. Highlights and filled boxes around words are
Word's shading, dashed and dotted frames Word's dashed and dotted borders, and a dashed line a picture. The file is checked against the PDF with
LibreOffice, ONLYOFFICE and Microsoft's Open XML validator, pictures pixel by pixel; edits made in Word don't come back
to the document. What Word can't reproduce exactly:
- a word longer than its table column, which Typst lets run past the cell, Word breaks inside the cell;
- equations: each word processor typesets math itself, so an equation can come out a little wider or taller than Typst's, and a line or a page break can move where a document has many of them. Typst's math font is embedded and named as the document's math font; whether Word uses it rather than Cambria Math is untested (no Word in the checks);
- numbers Word has no format for, Bengali and Eastern Arabic digits: list labels in them are text (not Word numbering), and page numbers in them come out in Western digits (Devanagari ones are Word's Hindi numbers);
- in LibreOffice only (Word isn't in the checks): equations come out black whatever their colour (its import drops the colour Word reads), and inline fractions are set at display size, so a line with one is taller;
- text decorations Word has no equivalent for, or sets otherwise: an overline, small capitals from the font, letter and word spacing, and a word framed by a box in a line (Word underlines it).
Google Docs opens the file with its own spacing: it has no exact line heights, so lines are spaced as multiples of the font's and its pages can break in other places. Pictures and the space around them keep their size there, so text doesn't run under a picture.
HTML
EngineDocument.exportHtml() returns Typst's HTML export: a complete HTML document, without the source anchors the
live preview uses. It is not sanitized. The model wrote it, so don't insert it into your page.
standaloneHtml(html, options) from @typstream/dom makes it a file that is safe to download and open:
- the renderer's theme, then the plugins' stylesheets (html-compat's, edu's), then your
stylesheets, all inline; - the root class
typstreamon<body>, so those styles apply; - a Content-Security-Policy as the first thing in
<head>, so whatever the document contains can't run scripts, load anything from the network or submit forms. Only inline styles anddata:images and fonts are allowed, plus the math font's origin if you give it as a URL; <meta http-equiv="refresh">removed, anddir="rtl"on<html>for a right-to-left language;- optionally the math font, so MathML renders properly wherever the file is opened.
The file isn't sanitized; the policy is what makes it safe. Re-serializing sanitized nodes for a file would invite mutation XSS, which the policy avoids.
Prop
Type
import { standaloneHtml } from "@typstream/dom";
const file = standaloneHtml(await doc.exportHtml(), { plugins: doc.plugins, title: "Worksheet" });doc.plugins is the document's resolved plugin list, so the file gets the same plugin stylesheets as the preview.
That file is Typst's HTML in a reading layout. To download what the HTML target shows, laid out as the pages,
use standalonePages(html, options) (in a browser). It lays the export out off-screen, as the HTML renderer does,
and writes the result into the same kind of file: the same policy and stylesheets, the renderer's CSS, and the Typst
fonts the pages use, embedded from typstFonts (pass the ones you give registerTypstFonts). The file runs no
script, so the layout is done when you export: it shows the pages one under the other at their size and prints a page
per sheet.
Prop
Type
import { standalonePages } from "@typstream/dom";
const file = await standalonePages(await doc.exportHtml({ anchors: true }), { plugins: doc.plugins, typstFonts });Export with anchors: true: html-compat writes each block's page settings, header and footer on the source anchors,
so without them the pages are A4 with none. A document that writes its page count (counter(page).final(), an exam's
"2 / 3") needs it as the input typstream-page-count: onPages gives the count the export was laid out on, to export
again with.
MountedTypstream.exportHtml(options?) and React's exportHtml(options?) do both steps, laid out as the pages, with
the component's or mount's plugins, stylesheets, theme and Typst fonts, compiling again with the page count until
it holds. options add to or override them, and can hold inputs too. pages: false gives standaloneHtml's
reading layout instead.
Prop
Type
To embed the math font, fetch the engine's copy once:
import { baseFonts } from "@typstream/engine-wasm/fonts";
const url = baseFonts.find((u) => u.pathname.includes("NewCMMath"));
const mathFont = new Uint8Array(await (await fetch(url!)).arrayBuffer());
const file = standaloneHtml(await doc.exportHtml(), { plugins: doc.plugins, mathFont });Embedded, it adds about 0.7 MB to the file. Given as a URL instead, the file stays small but needs that URL to be reachable when it's opened.
Source
exportSource() returns the healed source as a string, synchronously. It doesn't include the preamble or the files.
Save it to store the document, or offer it as a .typ download.
To compile the source elsewhere, give it what the preview had. For a document written with @typstream/edu, that
means its files and preamble (eduFiles, eduPreamble), or, with the Typst CLI, edu's package and an
#import "@typstream/edu:0.1.0": * line in front.
Errors
Exports reject with an ExportError. Its reason says what went wrong, and diagnostics holds the export's
diagnostics in input coordinates:
reason | Meaning |
|---|---|
diagnostics | The source has errors; they are in diagnostics. |
unsupported | The engine doesn't offer this format. |
timeout | The export ran past the final watchdog budget; the worker was replaced. |
crash | The worker died during the export. |
too-large | The input is longer than limits.maxLength (1 MiB by default). |
engine | The engine can't run, was disposed or refused the request, or the document was disposed. |
import { ExportError } from "@typstream/engine";
try {
await doc.exportPdf();
} catch (error) {
if (error instanceof ExportError && error.reason === "diagnostics") {
showErrors(error.diagnostics);
} else throw error;
}error.name is always "ExportError", if you'd rather not import the class.
A download button in React
"use client";
import { useState } from "react";
import type { TypstreamInfo } from "typstream";
const save = (data: BlobPart, type: string, name: string) => {
const url = URL.createObjectURL(new Blob([data], { type }));
const link = document.createElement("a");
link.href = url;
link.download = name;
link.click();
setTimeout(() => URL.revokeObjectURL(url), 0);
};
export function DownloadButtons({ t, disabled }: { t: TypstreamInfo; disabled: boolean }) {
const [error, setError] = useState<string | null>(null);
// An export opens a document that hasn't opened yet; it needs a mounted <Typstream>.
const off = !t.handle || disabled;
const run = async (download: () => Promise<void>) => {
setError(null);
try {
await download();
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
}
};
return (
<div>
<button
type="button"
disabled={off}
onClick={() =>
run(async () => {
const pdf = await t.exportPdf();
// TypeScript 5.7+ types Blob parts as ArrayBuffer-backed views.
save(pdf as Uint8Array<ArrayBuffer>, "application/pdf", "document.pdf");
})
}
>
PDF
</button>
<button
type="button"
disabled={off}
onClick={() =>
run(async () => save(await t.exportHtml({ title: "Document" }), "text/html", "document.html"))
}
>
HTML
</button>
<button
type="button"
disabled={!t.handle}
onClick={() => save(t.exportSource(), "text/plain", "document.typ")}
>
Typst source
</button>
{error && <p role="alert">{error}</p>}
</div>
);
}"use client";
import { Typstream, useTypstream } from "typstream";
import { DownloadButtons } from "./download-buttons";
export function Answer({ text, isStreaming }: { text: string; isStreaming: boolean }) {
const t = useTypstream();
return (
<>
<Typstream ref={t.ref} source={text} isStreaming={isStreaming} />
<DownloadButtons t={t} disabled={isStreaming} />
</>
);
}exportHtml already returns the standalone file, so the component needs nothing from @typstream/dom. typstream
doesn't re-export ExportError: check error.name === "ExportError", or install @typstream/engine to import the
class.
On the server
@typstream/node renders a document without a browser, on the same Typst build:
import { writeFile } from "node:fs/promises";
import { render } from "@typstream/node";
const result = await render(source, "pdf");
if (result.ok) await writeFile("document.pdf", result.data);
else console.error(result.diagnostics);render(source, format, options?) takes "pdf" (bytes), "docx" (bytes), "html" (Typst's HTML as a string) or
"svg" (one string per page), and the options every compile takes: preamble, files, inputs, timeoutMs and engine. A result is
{ ok: true, data, diagnostics, pageCount?, ms } or { ok: false, diagnostics, ms }. standaloneHtml is a string
transform, so it works on the server's HTML too. See @typstream/node and
the server fix loop.
Preloading the engine
Download and start the Typst engine before the first document appears, so it renders at once instead of waiting for the wasm and fonts.
Theming and styling
Light and dark themes, the CSS variables and classes typstream exposes, extra stylesheets, and the word fade-in and caret while streaming.