Typst
Typst is a Python binding to the Rust-based Typst typesetting system, designed as a modern, powerful, and easy-to-learn alternative to LaTeX. The `typst` library allows Python applications to programmatically compile Typst source files or content into various output formats such as PDF, PNG, and SVG. It boasts fast compile times due to incremental compilation and provides friendly error messages. The library is actively maintained, with version 0.14.8 currently available, and frequent releases.
Common errors
-
RuntimeError: Typst compilation failed: failed to compile: ... (diagnostic messages)
cause This generic runtime error indicates a problem within the Typst source code being compiled, such as syntax errors, missing files referenced in the Typst document, or other Typst language-specific issues.fixInspect the `e.message` (if catching `typst.TypstError`) or the full error output for specific diagnostic messages from the Typst compiler. Correct the Typst syntax, ensure all referenced files are present and correctly specified, and check for Typst breaking changes if recently upgraded. -
ModuleNotFoundError: No module named 'typst'
cause The Python `typst` library has not been installed or is not accessible in the current Python environment.fixInstall the library using pip: `pip install typst`. -
Error: expected expression ╭─[/main.typ:X:Y] │ X │ for i in ───╯ Error: expected semicolon or line break ╭─[/main.typ:Z:W] │ Z │ (1, 2, 3) { ────╯cause This Typst parser error occurs when there's a line break immediately after the `in` keyword in a `for` loop, before the iterable is specified. The parser expects the iterable on the same line or separated by an explicit semicolon.fixEnsure the iterable follows the `in` keyword on the same line, or explicitly terminate the `in` line with a semicolon if the iterable must start on a new line. Example: `#for i in (1, 2, 3) { ... }` or `#for i in; (1, 2, 3) { ... }`. -
Typst compilation error: failed to compile: error: unknown label 'my-label'
cause This error occurs when a label (e.g., `#label("my-label")`) is referenced (e.g., `@my-label`) within a Typst document, but the label itself is either not defined, misspelled, or not yet available in the compilation scope (e.g., in a separate file that hasn't been properly included/imported).fixVerify that the label is correctly defined and spelled in the Typst source. For multi-file projects, ensure that the file defining the label is accessible and compiled as part of the project, often by passing all relevant files in the dictionary input to `typst.compile()`.
Warnings
- breaking Typst 0.14.0 introduced several minor breaking changes in the underlying Typst language and compiler. Notable changes include labels, link URLs, and font lists no longer accepting empty values, `pdf.embed` being renamed to `pdf.attach`, and some bibliography styles being renamed. Documents written for older Typst versions might require adjustments.
- breaking Typst versions 0.14.0 and 0.14.1 of the underlying Rust compiler (used by `typst-py`) contained a memory handling vulnerability in the WebAssembly runtime used for plugins. Although considered hard to exploit, an upgrade is recommended.
- gotcha When compiling multi-file Typst projects, the `typst.compile()` function or `Compiler.compile()` method expects a dictionary where keys are filenames (e.g., 'main.typ', 'lib.typ') and values are their content as bytes. The main entry file should typically be keyed as 'main' or 'main.typ'.
- gotcha In Typst documents, imports are not global. If a package or module (e.g., `#import "@preview/physica:0.9.5": *`) is needed in multiple `.typ` files (e.g., chapters of a larger document), it must be explicitly imported in *each* file where its components are used. This differs from global import behaviors in some other languages.
Install
-
pip install typst
Imports
- typst
import typst
- Compiler
from typst import Compiler
Quickstart
import typst
import os
typst_content = """
#set page(width: 200pt, height: auto, margin: 1in)
#set text(font: "New Computer Modern", fill: black)
= Hello, Typst from Python!
This is a document compiled using the `typst` Python library.
#let data = (
("Item", "Value"),
("First", 100),
("Second", 200),
)
#table(
columns: 2,
align: (center, right),
stroke: .5pt,
..data.map(row => row.map(cell => if cell is str { strong(cell) } else { repr(cell) }))
)
#figure(
image("https://typst.app/assets/typst-logo.png", width: 50%),
caption: [The Typst logo.],
)
"""
# Compile to PDF and save to a file
try:
pdf_bytes = typst.compile(typst_content.encode('utf-8'))
output_path = "output.pdf"
with open(output_path, "wb") as f:
f.write(pdf_bytes)
print(f"Successfully compiled to {output_path}")
except typst.TypstError as e:
print(f"Typst compilation error: {e.message}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
# Using the Compiler class for multiple compilations
compiler = typst.Compiler()
try:
png_bytes = compiler.compile(typst_content.encode('utf-8'), format="png", ppi=144.0)
output_path_png = "output.png"
with open(output_path_png, "wb") as f:
f.write(png_bytes)
print(f"Successfully compiled to {output_path_png}")
except typst.TypstError as e:
print(f"Typst compilation error for PNG: {e.message}")
except Exception as e:
print(f"An unexpected error occurred during PNG compilation: {e}")