Typst

0.14.8 · active · verified Thu Apr 16

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates compiling Typst content from a Python string into a PDF file, and also using the `Compiler` class to output a PNG. It includes basic text, a table, and an image from a URL within the Typst source. Error handling for `typst.TypstError` is also shown.

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}")

view raw JSON →