Typsty

Render Typst documents to PDF, PNG and SVG right from Elixir!

Hex.pm GitHub Workflow Status (master) Coveralls master branch Support the project


Contents

Installation

Available in Hex, the package can be installed by adding typsty to your list of dependencies in mix.exs. It requires Elixir 1.18 or later.

def deps do
  [
    {:typsty, "~> 0.1.0"}
  ]
end

Typsty compiles documents with Typst 0.15 through a Rust NIF, which is downloaded precompiled for your platform, so you don't need Rust installed. The download is about 40 MB (82 MB unpacked, in priv/native), since it has both the NIF and the program Typsty.Pool runs, which each include Typst and its fonts.

Documentation can be found at https://hexdocs.pm/typsty.

Level Up Your Elixir Skills!

Everything I have learned building production Elixir systems ends up in one of two places: an open source library on Hex, or a book. The libraries are free and will stay that way. The books are what let me keep writing them.

If this library has been useful to you, picking up one of my books is the best way to support this library and the many others that I maintain. You'll also gain knowledge that took me years to attain!

Elixir For Finance — Learn how to navigate markets and trading without leaving the BEAM. Livebook for exploration, Explorer for dataframes, VegaLite for visualizations. This book goes through it all!

Elixir Patterns — The essential BEAM handbook for the busy developer. The patterns and mental models covered in this book teach you how to build scalable systems that can handle whatever production throw at them.

Programming Nerves — The best place to start if you are looking to get your own hardware projects up and running with Elixir and Nerves. I doubt you'll find a more fun and enjoyable hardware book out there!

Build a Weather Station with Elixir and Nerves — A project-based introduction to Nerves. Wire up the sensors, capture readings and then pipe the data into a time series database that can be visualized with Grafana.

Using Typsty

A document module does use Typsty and defines render/1 with the ~TYPST sigil, like a LiveView:

defmodule MyApp.Invoice do
  use Typsty

  def render(assigns) do
    ~TYPST"""
    #set page(paper: "us-letter")
    #image("logo.png", width: 3cm)

    = Invoice #assigns.number

    Billed to #assigns.customer.name on #assigns.issued_on.display("[month repr:long] [day], [year]").

    #table(
      columns: (1fr, auto),
      [*Item*], [*Price*],
      ..assigns.items.map(item => (item.name, [\$#item.price])).flatten(),
    )

    *Total: \$#assigns.items.map(item => item.price).sum()*
    """
  end
end

Or it leaves render/1 out and keeps the template in a .typ file next to the module, with the same base name (invoice.ex and invoice.typ), like LiveView's colocated templates, which lets editors that know Typst highlight it.

Render it to PDF, PNG (one image per page) or SVG (one per page):

assigns = %{
  number: 1042,
  issued_on: ~D[2026-11-23],
  customer: %{name: "Acme Corp"},
  items: [%{name: "Widget", price: Decimal.new("19.99")}, %{name: "Gadget", price: Decimal.new("5.01")}]
}

files = %{"logo.png" => File.read!(Application.app_dir(:my_app, "priv/static/images/logo.png"))}

{:ok, pdf} = MyApp.Invoice.to_pdf(assigns, files: files)
{:ok, [first_page | _]} = MyApp.Invoice.to_png(assigns, files: files, ppi: 300)
{:ok, svgs} = MyApp.Invoice.to_svg(assigns, files: files)

Each one has a bang variant (to_pdf!/2 and so on) that raises instead of returning an error.

Templates are checked when your code compiles: a syntax error in a ~TYPST sigil or a .typ template fails the build, pointing at the line in your file. A component that breaks the rules for components (see Components) fails the build the same way, with invalid component: ….

For templates that don't live in a module, such as ones stored in a database, render a string of Typst source with Typsty.to_pdf/3, Typsty.to_png/3 and Typsty.to_svg/3, and check it with Typsty.validate/1:

{:ok, pdf} = Typsty.to_pdf("= Hello #assigns.name", %{name: "World"})
{:ok, [page]} = Typsty.to_png("= Hello #assigns.name", %{name: "World"}, ppi: 300)

The assigns are always a map, and the options come after them.

Assigns

The template reads the assigns from a dictionary named assigns, the way a LiveView's @number is assigns.number: assigns.number, assigns.customer and assigns.items above. You can tell at a glance what came from Elixir and what the template defines, and an assign can't shadow anything in Typst (an assign named title is assigns.title, and title is still Typst's). Typst gets the data itself rather than code generated from it, so nothing needs escaping, and the template can loop over lists, read fields, do arithmetic and format dates:

Elixir Typst
nil, true, false none, true, false
integers and floats int (64-bit) and float
strings str
atoms str (:paid becomes "paid")
lists and tuples array
maps dictionary, with string keys, sorted
Date, Time, NaiveDateTime, DateTime datetime (DateTime keeps its wall time)
Decimal decimal
MapSet, Range, Date.Range array
other structs see Typsty.Encoder

The assigns are a map with atom or string keys. A template reads keys that aren't Typst identifiers with at (assigns.at("invoice number")), and assigns that may be missing with a default:

#let subtitle = assigns.at("subtitle", default: none)

Keyword lists are lists of tuples, so they become arrays of pairs: pass maps for dictionaries. A Date.Range becomes an array of the dates it steps through, so a template shows a range of days with assigns.period.first() and assigns.period.last(). A MapSet becomes a sorted array: dates, times and decimals in order of their values, anything else in Erlang's term order. Typst's datetimes have no time zone or fractions of a second, so a DateTime keeps its wall time and times are truncated to the second, and its decimals have 28 significant digits.

Other structs are passed when they implement Typsty.Encoder, so that their internal fields (an Ecto schema's metadata, or a password hash) don't reach templates by accident. Derive it to pass a struct as a dictionary of its fields, or some of them:

defmodule MyApp.Customer do
  @derive {Typsty.Encoder, only: [:name, :email]}
  defstruct [:name, :email, :password_hash]
end

or implement it to pass a struct differently:

defimpl Typsty.Encoder, for: MyApp.Money do
  def encode(money), do: MyApp.Money.to_string(money)
end

A template that uses a few assigns a lot can give them short names, by destructuring them at its top. The names are then the template's own, so pick ones that don't hide anything it uses from Typst, such as title or page:

#let (customer, items) = assigns

= Invoice for #customer.name

assigns is bound at the top of the template, like a #let binding, so it's only visible in the template itself. Pass the files it imports, such as components, the values they need as arguments, which keeps them independent of where their data comes from:

#import "components/tables.typ": line-items
#line-items(assigns.items)

(Imported files other than components can also read the assigns from sys.inputs.assigns.)

render/1 gets the assigns first, so it can compute values for the template with all of Elixir:

def render(assigns) do
  assigns = Map.put(assigns, :due_on, Date.add(assigns.issued_on, 30))

  ~TYPST"""
  Due on #assigns.due_on.display()
  """
end

Components

Reusable parts of documents, such as tables, letterheads, headers and footers, are components: Typst functions in a module that does use Typsty.Component. The source is in a .typ file next to the module (tables.ex and tables.typ), or in a render/0 with the ~TYPST sigil:

defmodule MyApp.Documents.Tables do
  use Typsty.Component

  def render do
    ~TYPST"""
    #let line-items(items, currency: "$") = table(
      columns: (1fr, auto),
      [*Item*], [*Price*],
      ..items.map(item => (item.name, [#currency#item.price])).flatten(),
    )
    """
  end
end

Headers and footers go in a template function, which takes the document's content as its last argument and lays out the pages around it:

// lib/my_app/documents/letterhead.typ, next to letterhead.ex
#let letterhead(title: none, logo: none, body) = {
  set page(
    header: [#logo #h(1fr) #title],
    footer: context [Page #counter(page).display() of #counter(page).final().first()],
  )
  body
}

A document lists its components, and imports each one from components/<name>.typ, where the name is the last part of the module's name, in snake case. A show rule applies the letterhead to everything after it:

defmodule MyApp.Invoice do
  use Typsty, components: [MyApp.Documents.Letterhead, MyApp.Documents.Tables]

  def render(assigns) do
    ~TYPST"""
    #import "components/letterhead.typ": letterhead
    #import "components/tables.typ": line-items
    #show: letterhead.with(title: [Invoice #assigns.number], logo: image("logo.png", height: 1cm))

    #line-items(assigns.items)
    """
  end
end

Components only define things, and only get data as arguments. Both are checked when they compile. Their top level can only have definitions (#let) and imports (#import), so a component can't be used as a partial. Set and show rules go inside functions, like the letterhead's set page(...). And they can't read sys.inputs, where the document's assigns are: they can only use sys to read its other fields, and can't use eval.

A component's own files, such as its images and data, go in a folder next to it with the same base name (letterhead/ next to letterhead.ex). Renders get them at components/<name>/. Paths in a component are relative to components/, where its .typ file is, so it reads them as image("letterhead/seal.svg"). They're read when the component compiles and kept in its module, so they work in releases and in a Typsty.Pool. Paths to them written as strings, such as image("letterhead/seal.svg"), are checked then too. Files that change from document to document, like the logo above, are passed as arguments instead: pass the file itself (image("logo.png")), since a path given to a component would be read relative to components/.

Errors in a component point at the line in its .typ file or its sigil. Documents only depend on their components at runtime, so changing a component doesn't recompile them. A component can list the components it imports (use Typsty.Component, components: [MyApp.Documents.Brand]), and templates rendered from strings get components with the :components option. See Typsty.Component for the details.

Files

Images, data files and other .typ files are passed as binaries in the :files option. They live in a virtual file system for the render and are never written to disk:

MyApp.Report.to_pdf(assigns,
  files: %{
    "logo.png" => logo,
    "charts/revenue.svg" => chart_svg,
    "data/sales.csv" => csv,
    "styles.typ" => File.read!(Application.app_dir(:my_app, "priv/typst/styles.typ"))
  }
)
#import "styles.typ": callout
#image("charts/revenue.svg")
#let sales = csv("data/sales.csv")

Name files yourself, rather than with names that come from users (an upload's file name, say): a .typ file in :files takes the place of the one the template imports, which would let a user run their own Typst code. Use fixed names, like upload.png, or uploads/1.png, uploads/2.png and so on, numbered within the render rather than by id, since every new name counts against a limit for the life of the VM (see below). (Components can't be replaced that way: components/ is reserved for them, so :files can't have files there, and it isn't read from :root.)

Without the :root option, a document can only read the files it's given. Set :root to a directory to also read files from it (files in :files take precedence). Documents can't read outside it, even through symbolic links, unless a link is swapped in while a document reads it, so don't set :root to a directory that others can write to. Documents may read files of up to 512 MiB from it. main.typ is the template itself.

Typst keeps every file path it has seen for the life of the VM, and has room for 65,535 of them, so use stable names like logo.png rather than a new unique name for every render; a template that builds paths from data, like image("photos/" + assigns.id), uses a new one for every id. Typsty stops a render that reads more than 10,000 different files, refuses new names in :files once 50,000 different ones have been given over the life of the VM, and stops renders that need a new path once the table is nearly full, rather than let it overflow; inside the VM, that lasts until the VM restarts, while a Typsty.Pool replaces its workers. Typst keeps label names and bibliography keys for the life of the VM too, so make labels from fixed names (<total>), not from data such as ids.

Renders inside the VM can't read PDF files (to use a PDF as an image, say), or SVG images that contain other SVG images, since decoding them can crash the VM. Renders in a Typsty.Pool can.

Fonts

Documents can use the fonts installed on the system, the fonts that come with Typst (Libertinus Serif, New Computer Modern, New Computer Modern Math and DejaVu Sans Mono), and fonts in the directories given with :font_paths. For documents that render the same on every machine, ship your fonts with your application and turn system fonts off:

# config/runtime.exs
config :typsty, font_paths: [Application.app_dir(:my_app, "priv/fonts")], system_fonts: false

Fonts are scanned once for each combination of font options, and the fonts found for the 32 combinations used most recently are kept. Font files are only read the first time a document uses them. To scan them ahead of the first render, call Typsty.font_families/1 when your application starts. It also returns the font families that were found, which helps when a font isn't being picked up.

Packages

Templates can import Typst packages. Download them into your project with mix typsty.packages.get:

mix typsty.packages.get @preview/cetz:0.4.2
* Fetched @preview/cetz:0.4.2
* Fetched @preview/oxifmt:1.0.0 (imported by @preview/cetz:0.4.2)

Downloaded 2 of 2 packages into priv/typst/packages. Templates can import them when the :package_paths option includes that directory, in config/runtime.exs:

    config :typsty, package_paths: [Application.app_dir(:my_app, "priv/typst/packages")]

Packages are saved in priv/typst/packages (change it with --path), laid out as namespace/name/version like Typst's own package directories, so they ship with your releases. Packages that a package imports are fetched too, and a package given without a version (@preview/cetz) gets its latest version that works with the Typst version Typsty uses (Typsty.typst_version/0).

Point the :package_paths option at the directory, in config/runtime.exs:

config :typsty, package_paths: [Application.app_dir(:my_app, "priv/typst/packages")]
#import "@preview/cetz:0.4.2": canvas, draw

To keep the list of packages in your repository, for CI and Docker builds, list them in your config, with their versions, and run the task without arguments (in a Docker build, in the build stage, before mix release):

# config/config.exs
config :typsty, packages: ["@preview/cetz:0.4.2"]

Typsty never downloads packages while rendering, so documents don't wait on the network and always use the package versions you ship. A template that imports a package that isn't there fails with an error that says which package to fetch and which directories were searched. Your own packages can go in the same directories, under a namespace such as local.

Errors

A syntax error fails the build with a Typsty.SyntaxError:

** (Typsty.SyntaxError) invalid Typst syntax: lib/my_app/invoice.ex:12:18: unclosed delimiter

    #let total = (1, 2
                 ^

Errors that depend on the data, such as a missing assign or a value of the wrong type, are returned as a Typsty.RenderError with the diagnostics Typst reported, pointing at the line in your module or .typ file, with hints:

{:error, %Typsty.RenderError{reason: :typst} = error} = MyApp.Invoice.to_pdf(%{number: 1042}, files: files)
Exception.message(error)
#=> failed to render the Typst document:
#=>
#=> lib/my_app/invoice.ex:11:24: dictionary does not contain key "customer"
#=>   hint: there's no "customer" in the assigns. Pass it from Elixir, or read it with `assigns.at("customer", default: none)` if it's optional

The error's :reason tells Typst's errors (:typst) apart from renders that timed out (:timeout) or couldn't start in time because the server was busy (:busy), so a web application can answer those with a 503 and a retry. See Typsty.RenderError for the others. Invalid arguments, such as an unknown option or a value that can't be passed to Typst, raise an ArgumentError.

Typst's warnings, such as an unknown font family, are logged. Every render also emits telemetry events (see Typsty.Telemetry).

Errors are written for developers: their messages can quote the assigns, and name paths on the server (the :root directory's, say). Log them, and show users a message of your own.

Running Typst inside the BEAM

Typsty runs Typst in a NIF, inside your VM, so a crash in it would take the whole VM down. It's built to protect the VM from what you render with:

Typst decodes many formats, with many libraries, and the checks can't promise to catch every hostile file. Render documents that read files from people you don't trust, such as uploads, in a Typsty.Pool with a :memory_limit. Only the files a document reads are checked: data a template turns into bytes itself (image(bytes(assigns.svg)), or bytes from a list of integers) isn't, so pass such data as a file. An SVG can read other files in the project by linking them, so don't give documents a :root that holds other people's files.

A template, though, is code. Like any code, it can loop for a long time, and it can ask for as much memory as it likes. An allocation that fails ends the VM at once, whatever memory is free (a template that asks for an exabyte doesn't wait for the machine to run out), and some of Typst's libraries end the process on a panic in the middle of drawing. Typsty can't stop all of that inside the VM. What a template does with its data decides how much work it does:

Which to use

Rendering inside the VM is the right choice for data that's well validated: data your application built itself, or that came from users through an Ecto changeset that cast its types and checked its sizes (validate_number/3, validate_length/3) before it was saved to your database.

Favor a Typsty.Pool with a :memory_limit for input from untrusted users that isn't well validated, such as request parameters passed to a template as they are, or uploaded files, and for templates you don't write. In a pool, the worst a render can do is end its worker: the render returns an error, and the worker is replaced.

Rendering in separate processes

Typsty.Pool runs renders in a pool of separate OS processes, which it can end at any moment. It's the way to render input from untrusted users that isn't well validated (see Which to use), since it gives you guarantees the NIF can't:

Add a pool to your supervision tree, and render with it:

children = [
  {Typsty.Pool, name: MyApp.TypstPool, size: 4, memory_limit: 1_000_000_000}
]
MyApp.Invoice.to_pdf(assigns, pool: MyApp.TypstPool, timeout: 10_000)

Or render every document with it:

config :typsty, pool: MyApp.TypstPool

Renders return what they return without a pool: the same output and the same warnings and errors, pointing at the same lines (and they can read PDF files, and SVGs that contain SVGs). A worker that's stopped is replaced, and workers end when the pool stops, when the process rendering with them exits and when the VM exits. A pool that stops before or during a render returns an error to the process waiting for it. A new worker loads the fonts renders use by default before it takes renders.

The pool isolates crashes and memory use, not privileges: its workers run as the same user as the VM. They get only the environment variables that finding fonts needs, not the VM's (such as secrets in DATABASE_URL).

The memory limit counts everything a worker allocates, including the fonts it has loaded and Typst's caches, and each worker keeps its own, so leave room for them; see Typsty.Pool. Without a memory limit, a render that allocates without bound can make the system run out of memory, and the system may then end the BEAM rather than the worker.

The pool's workers run typsty_worker, a program built from the same code as the NIF, which comes with it. Rendering in a worker copies the template, the assigns, the files and the output between processes, and a worker that replaces one that was stopped starts with empty caches, so it's a little slower than the NIF. See Typsty.Pool for its options.

Formatting

Typsty.Formatter is a mix format plugin that formats ~TYPST sigils and .typ files with typstyle. Add it to your .formatter.exs:

[
  plugins: [Typsty.Formatter],
  inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs,typ}"]
]

To leave a sigil as it is, use the noformat modifier: ~TYPST"""..."""noformat. See Typsty.Formatter for its options.

Examples

The examples directory has documents that web applications commonly generate, with sample data: an invoice, a report with charts, a cheat sheet, an account statement, event tickets, shipping labels and a certificate. They share components for their branding and letterhead, and use packages for charts, QR codes and barcodes. See its README to render them.

Configuration

Every rendering option except :files and :components can be set in your application config, as a default for every render:

config :typsty,
  root: nil,
  font_paths: [],
  system_fonts: true,
  embedded_fonts: true,
  package_paths: [],
  ppi: 144,
  pdf_standards: [],
  timeout: 60_000,
  pool: nil,
  # Renders inside the VM at once; defaults to the number of dirty CPU schedulers
  max_concurrent_renders: 8,
  log_warnings: true,
  # Packages for mix typsty.packages.get to fetch (see Packages)
  packages: []

Options are checked with NimbleOptions, in the config as well as in calls: an invalid value, or an unknown option (a typo such as font_path), raises an ArgumentError that names the option, and says when it comes from the config. See Typsty for each option.

Paths are expanded relative to the current directory when a document renders, so in a release, set them in config/runtime.exs with Application.app_dir/2:

config :typsty, font_paths: [Application.app_dir(:my_app, "priv/fonts")]

:pdf_standards takes Typst's standard names, such as "a-2b" for PDF/A-2b and "ua-1" for PDF/UA-1. PDF/A needs the document's creation date, which is the time of the render unless the template sets #set document(date: ...).

datetime.today() is the date in UTC. For a date in the user's time zone, pass it as an assign.

Building the NIF from source

The NIF is downloaded precompiled for macOS (Apple Silicon and Intel), Linux (x86-64 and ARM64, glibc and musl) and Windows (x86-64); Typsty.Pool is less tested on Windows than on macOS and Linux. On Alpine Linux, the NIF needs libgcc (apk add libgcc, which libstdc++ brings along). To build it from source instead, install Rust 1.92 or later, add Rustler to your dependencies:

{:rustler, ">= 0.0.0", optional: true}

and set TYPSTY_BUILD=1 when compiling:

TYPSTY_BUILD=1 mix deps.compile typsty --force --include-children

or, to always build it from source, configure RustlerPrecompiled:

config :rustler_precompiled, :force_build, typsty: true

Development versions of Typsty (such as a Git dependency on master) are always built from source, so they need Rust and the Rustler dependency too, as does a Git dependency on a release's tag (with TYPSTY_BUILD=1).

If downloading the precompiled NIF fails with a TLS error such as unsupported_certificate, update Erlang/OTP: some patch releases (such as 27.2) don't accept the certificates GitHub's downloads use. Building from source works too.

Attribution