typst_template/lib.rs
1//! Generate PDFs with [Typst](https://typst.app) straight from your Rust types.
2//!
3//! Derive [`ToDict`](macro@ToDict) on a struct and it becomes a Typst input
4//! dictionary — feed it to a `.typ` template as `sys.inputs` and render to PDF,
5//! with no hand-written dict building. The [`ToValue`] / [`ToDict`] traits do
6//! the Rust-to-Typst value conversion, with optional `chrono`, `time`,
7//! `rust_decimal`, `serde_json`, and `uuid` support.
8//!
9//! Rendering uses two parts:
10//!
11//! - [`WorldBase`] — built once; loads fonts and roots file access at a directory.
12//! - [`ConcreteWorld`] — one per document; attaches this generation's `sys.inputs` and any virtual
13//! in-memory files (images, generated assets, …).
14//!
15//! # Example
16//!
17//! ```
18//! use typst_template::{ToDict, WorldBaseConfig};
19//!
20//! #[derive(ToDict)]
21//! struct Invoice {
22//! client: String,
23//! total: i64,
24//! }
25//!
26//! // A base that only uses the embedded fonts (no system font lookup).
27//! let base = WorldBaseConfig::new(".").system_fonts(false).build();
28//!
29//! let world = base
30//! .concrete("main.typ")
31//! .file("main.typ", "Invoice for #sys.inputs.client: #sys.inputs.total EUR")
32//! .inputs(Invoice { client: "ACME".into(), total: 42 })
33//! .build();
34//!
35//! let pdf = world.render_pdf_default().output.expect("render succeeds");
36//! assert_eq!(&pdf[..4], b"%PDF");
37//! ```
38//!
39//! # Reusing a base
40//!
41//! Build the [`WorldBase`] once, then derive a [`ConcreteWorld`] per document:
42//!
43//! ```
44//! use typst_template::WorldBaseConfig;
45//!
46//! let base = WorldBaseConfig::new(".").system_fonts(false).build();
47//!
48//! for name in ["Alice", "Bob"] {
49//! let pdf = base
50//! .concrete("main.typ")
51//! .file("main.typ", "Hello, #sys.inputs.name!")
52//! .input("name", name)
53//! .build()
54//! .render_pdf_default()
55//! .output
56//! .expect("render succeeds");
57//! assert_eq!(&pdf[..4], b"%PDF");
58//! }
59//! ```
60//!
61//! # `datetime.today()`
62//!
63//! With no `chrono`/`time` feature, `datetime.today()` is disabled by default
64//! and returns nothing; set a value with
65//! [`today`](ConcreteWorldBuilder::today). With `chrono` or `time` enabled it
66//! defaults to the system clock ([`today_system`](ConcreteWorldBuilder::today_system)),
67//! and [`today_system_in`](ConcreteWorldBuilder::today_system_in) (with
68//! `chrono-tz` or `time-tz`) pins "local" to a DST-aware named zone.
69//!
70//! Note: with the `time` backend, `today_system` falls back to UTC when the
71//! OS-local offset is unavailable (e.g. in a multithreaded process); use a named
72//! zone (or `chrono`) for a specific local zone.
73//!
74//! # Features
75//!
76//! - `derive` *(default)* — the [`ToDict`](macro@ToDict) derive macro.
77//! - `chrono` — [`ToValue`] for `chrono` date/time types, plus a system-clock `datetime.today()`.
78//! - `time` — [`ToValue`] for `time` date/time types, plus a system-clock `datetime.today()`.
79//! `chrono` takes precedence if both are enabled.
80//! - `chrono-tz` / `time-tz` — named-time-zone support for
81//! [`today_system_in`](ConcreteWorldBuilder::today_system).
82//! - `rust_decimal` — [`ToValue`] for `rust_decimal::Decimal`.
83//! - `serde_json` — [`ToValue`]/[`ToDict`] for `serde_json` values.
84//! - `uuid` — [`ToValue`] for `uuid::Uuid`.
85//!
86//! # Typst compatibility
87//!
88//! This release targets **Typst 0.15**. The re-exported [`typst`] crate is part
89//! of the public API, so moving to a new Typst version is a breaking change; see
90//! the README for the version compatibility table.
91
92#![cfg_attr(docsrs, feature(doc_cfg))]
93#![forbid(unsafe_code)]
94#![warn(missing_docs, missing_debug_implementations)]
95
96// Let the `ToDict` derive refer to this crate as `::typst_template` even from
97// within the crate's own tests and examples.
98extern crate self as typst_template;
99
100mod convert;
101mod value;
102mod world;
103
104/// Implementation details used by the [`ToDict`](macro@ToDict) derive. Not part
105/// of the public API.
106#[doc(hidden)]
107pub mod __private {
108 pub use crate::value::merge_dict;
109}
110
111// Re-export the time-zone crates so callers can name the zone passed to
112// `today_system_in` without depending on them directly.
113#[cfg(feature = "chrono-tz")]
114#[cfg_attr(docsrs, doc(cfg(feature = "chrono-tz")))]
115pub use chrono_tz;
116#[cfg(feature = "time-tz")]
117#[cfg_attr(docsrs, doc(cfg(feature = "time-tz")))]
118pub use time_tz;
119pub use typst::diag::{SourceDiagnostic, SourceResult, Warned};
120pub use typst::foundations::{Dict, Str, Value};
121pub use typst_pdf::PdfOptions;
122/// Derives [`ToDict`](trait@ToDict) (and, through it, [`ToValue`]) for a named
123/// struct. See the [derive crate](typst_template_derive::ToDict) for the full list
124/// of `#[typst(...)]` attributes.
125///
126/// ```
127/// use typst_template::{ToDict, ToValue, Value};
128///
129/// fn cents(amount: i64) -> Value {
130/// Value::Str(format!("{}.{:02}", amount / 100, amount % 100).into())
131/// }
132///
133/// #[derive(ToDict)]
134/// struct Meta {
135/// locale: String,
136/// }
137///
138/// #[derive(ToDict)]
139/// #[typst(rename_all = "camelCase")]
140/// struct Invoice {
141/// client_name: String,
142/// #[typst(rename = "amount", with = "cents")]
143/// amount_cents: i64,
144/// #[typst(skip)]
145/// internal_id: u64,
146/// #[typst(flatten)]
147/// meta: Meta,
148/// }
149///
150/// let dict = Invoice {
151/// client_name: "ACME".into(),
152/// amount_cents: 1050,
153/// internal_id: 7,
154/// meta: Meta { locale: "hr".into() },
155/// }
156/// .into_dict();
157///
158/// assert_eq!(dict.get("clientName").unwrap(), &Value::Str("ACME".into()));
159/// assert_eq!(dict.get("amount").unwrap(), &Value::Str("10.50".into()));
160/// assert_eq!(dict.get("locale").unwrap(), &Value::Str("hr".into())); // flattened
161/// assert!(dict.get("internalId").is_err()); // skipped
162/// ```
163#[cfg(feature = "derive")]
164#[cfg_attr(docsrs, doc(cfg(feature = "derive")))]
165pub use typst_template_derive::ToDict;
166pub use value::{ToDict, ToValue};
167#[cfg(any(feature = "chrono-tz", feature = "time-tz"))]
168#[cfg_attr(docsrs, doc(cfg(any(feature = "chrono-tz", feature = "time-tz"))))]
169pub use world::Zone;
170pub use world::{ConcreteWorld, ConcreteWorldBuilder, WorldBase, WorldBaseConfig};
171// Re-export the Typst crates and the handful of types that appear in this
172// crate's public API, so downstream users don't need to depend on them
173// directly or match versions by hand.
174pub use {typst, typst_layout, typst_pdf};