Skip to content

custom backend renderers by exposing PagedDocument #9064

Open

Description

@ben-hansske

Description

It would be really helpful if it where possible to convert content to a serialized version of typst_layout::PagedDocument from within the typst language itself. Then custom backends for rendering to niche file formats could be written in pure typst or as a wasm plugin.

Proposal

I think the best place in typst current standard library might be the document function. There are two changes that are necessary to achieve a reasonable interface.

  1. If the path is set to none, then document should return the bytes of the document instead of writing them to a file. This could also be useful if somebody wants to create a raster image with typst and then use the resulting image inside of image.
  2. Add an additional variant to format which would be something like paged-document, which produces a cbor encoded representation of PagedDocument and returns it as bytes. Returning an encoded representation instead of a data structure makes it more coherent with 1.

Example

#let content  = [Hello World]
#let bytes = document(none, format: "paged-document", content)  // layout the conten
#let doc = cbor(bytes)                                                                                  // decode the serialized PagedDocument
#let rendered = custom-renderer(doc)                                                    // Do some custom processing to get the bytes of the final output
#asset("doc.gcode", rendered)                                                                  // write to a file

Alternatively, another function could be introduced, that turns content into PagedDocument.

Challenges

  • Depending on the inner working of typst, 1. could need some major changes to work properly. So first question: do you think this is even possible and reasonable?
  • PagedDocument is a complex data structure containing many Arcs. All of these need to be converted to integers indexing an array for serialization.
  • If PagedDocument changes in the future, will then result in breaking changes since it is exposed. However, this is likely not a feature that will be widely used. The few breaking packages that depend on it should be easy to fix in most cases.

I could see myself implementing the above if you want me to.
How do you feel about the above? Do you think there are better ways to achieve something similar?

Use Case

I want to use typst to directly produce gcode for a laser engraver. It would be really helpful if it where possible to have access to typst_layout::PagedDocument from within the typst language itself, so that custom backends like this could be written in pure typst or as a wasm plugin.

Activity

  1. added
    feature request
    on Nov 12, 2026
  2. gin49008-pixel commented on Nov 12, 2026

    @gin49008-pixel

    Using Typst to drive a laser engraver is a really cool use case! That said, exposing content -> PagedDocument inside the Typst language itself runs into several fundamental architectural and maintenance blockers - and fortunately, Typst's existing SVG backend already solves the hardest parts of this problem much more cleanly.


    Why content -> PagedDocument inside Typst is infeasible

    1. Evaluation vs. Layout Lifecycle (and Incremental Memoization):
      Typst’s compiler pipeline strictly separates evaluation (executing Typst code to produce content) from layout (resolving context, counters, query(), and page breaking into a PagedDocument). Allowing user code to trigger a full layout pass mid-evaluation and inspect the resulting PagedDocument creates a circular dependency between evaluation and layout. It would break comemo’s fine-grained incremental caching, complicate context / state / counter scoping (does the inner layout share counters with the outer document?), and clash with multi-target compilation (e.g., evaluating inside an HTML export target).
    2. Purity & Sandboxing (document / #asset):
      In Typst, document is a set-rule element for metadata (title, author, keywords), not an export function. By design, Typst evaluation is pure and deterministic—it cannot write arbitrary files to disk (like a hypothetical #asset("doc.gcode", ...)), as that would break reproducibility and sandboxing in the web app and build tools.
    3. PagedDocument is an unstable internal IR, not a clean geometry format:
      Even if serialized to CBOR, PagedDocument isn't a flat list of vector paths. It contains nested Frame trees, SourceSpans, image buffers, and raw font references + shaped glyph IDs. To generate G-code from PagedDocument, your WASM plugin would still have to parse OpenType font tables (ttf-parser), extract glyph outlines, apply Transform matrices, and flatten text into curves. Meanwhile, locking PagedDocument’s internal structure into a serialized format would make routine layout refactors in Typst breaking changes.

    Recommended Alternative: Use the SVG Backend

    Typst’s SVG exporter (typst-svg) already performs the exact lowering step you need: it traverses PagedDocument, resolves all nested frame transforms, converts all text glyphs into vector outlines (<path> elements), and outputs clean 2D vector geometry.

    Depending on how integrated you want the workflow to be, there are two straightforward ways to do this today:

    1. CLI Pipeline (typst compile + svg2gcode / vpype)

    You can compile your Typst document directly to SVG pages and pipe them into existing vector-to-G-code tools:

    # Export each page as a clean vector SVG (no background fill)
    typst compile engraving.typ "page-{p}.svg"
    
    # Convert to G-code using an existing CLI tool like svg2gcode or vpype-gcode
    svg2gcode page-1.svg -o page-1.gcode
    

    (Tip: Add #set page(fill: none) in your Typst source so the SVG backend doesn't emit a full-page white background rectangle that your laser converter has to filter out.)

    2. Custom Rust Wrapper (typst + typst-svg + usvg)

    If you want a single self-contained binary or custom G-code rules (e.g., mapping specific stroke colors in Typst like stroke: red to cut passes and stroke: blue to engraving passes):

    • Use the typst and typst-svg crates directly in Rust to compile your .typ file and call typst_svg::svg(&page).
    • Parse the resulting SVG with usvg (which simplifies all <use> glyph symbols, transforms, and shapes into flat Bézier paths with stroke/fill attributes) and walk the paths to emit your G-code.

    This gives you full access to Typst's layout engine and typography without needing any changes to the Typst language or exposing compiler internals.

  3. ben-hansske commented on Nov 12, 2026

    @ben-hansske
    Author

    Allowing user code to trigger a full layout pass mid-evaluation and inspect the resulting PagedDocument creates a circular dependency between evaluation and layout.

    I don't think this is an issue, at least not conceptually. Yes, it requires evaluation and layouting to be mixed up. But layouting is (or at least should be) perfectly pure, which should play very nice with memoization. document is already an export function (https://typst.app/docs/reference/model/document/) with the experimental bundle feature, that respects context / state and counter. Same goes for asset (https://typst.app/docs/reference/model/asset/). Also the code that produces the content is not the same code that consumes it, so there is no circular dependency.
    The only issue I can see, is that this change might requires some restructuring of the compilers code.

    your WASM plugin would still have to parse OpenType font tables

    Fair enough, but this is some work.

    Use the SVG Backend

    I have 3 issues that svg2gcode can't solve.

    1. It does not respect clipping paths which are generated by box.
    2. It can't deal with text produced by typst.
    3. It cannot deal with filled paths and does not produce extra tool paths for hatching the infill.

    Custom Rust Wrapper

    While this is a reasonable solution, it doesn't allow this to be a typst package that can pulled in simply via an import statement. I would like to avoid that. Also this Issue #8895 might benefit from the proposed changes, but I am not familiar with JATS. This is not only about producing gcode. Instead it could be also possible to create odf or docx documents and other file formats.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature request

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions