Skip to content

Repository files navigation

NTypst

github nuget build status

A C# wrapper for the Typst compiler. Compile Typst markup to PDF, PNG, SVG, and HTML from .NET.

Usage

using NTypst;

byte[]? ResolveFile(string path)
{
    var fullPath = Path.GetFullPath(Path.Combine(".", path.TrimStart('/')));
    return File.Exists(fullPath) ? File.ReadAllBytes(fullPath) : null;
}

using var world = new TypstWorld(sourceResolver: ResolveFile, fileResolver: ResolveFile);
world.AddSystemFonts();
world.SetMain("/main.typ");

var result = world.CompilePaged();
using var document = result.Document;

File.WriteAllBytes("output.pdf", document.ExportPdf());

Inline source

using System.Text;
using NTypst;

var source = "= Hello from C#\nThis is *Typst*.";

using var world = new TypstWorld(
    sourceResolver: path => path == "/main.typ" ? Encoding.UTF8.GetBytes(source) : null,
    fileResolver: _ => null);

world.AddSystemFonts();
world.SetMain("/main.typ");

var result = world.CompilePaged();
using var document = result.Document;

File.WriteAllBytes("output.pdf", document.ExportPdf());

Export formats

// PDF
byte[] pdf = document.ExportPdf();

// PNG (per page)
byte[] png = document.ExportPng(pageIndex: 0, pixelsPerPoint: 3.0f);

// SVG (all pages merged)
string svg = document.ExportSvg();

// SVG (single page)
string svgPage = document.ExportSvg(pageIndex: 0);

HTML compilation

var result = world.CompileHtml();
using var htmlDoc = result.Document;
string html = htmlDoc.Export();

Error handling

try
{
    var result = world.CompilePaged();
}
catch (TypstCompilationException ex)
{
    foreach (var diag in ex.Diagnostics)
    {
        Console.Error.WriteLine($"{diag.Severity}: {diag.Message}");
        foreach (var hint in diag.Hints)
            Console.Error.WriteLine($"  Hint: {hint}");
    }
}

Warnings

Successful compilations may still produce warnings:

var result = world.CompilePaged();

foreach (var warning in result.Warnings)
    Console.WriteLine($"Warning: {warning.Message}");

Building from source

Requires Rust and .NET 10 SDK.

cd native && cargo build
cd .. && dotnet build

To run the example:

LD_LIBRARY_PATH=native/target/debug dotnet run --project examples/NTypst.Examples

License

MIT

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages