Commit: cac20b7
Parent: 78a5ebb

Embedd Typst rendering

Mårten Åsberg committed on 2026-03-20 at 19:48
Cargo.lock +0 -226
diff --git a/Cargo.lock b/Cargo.lock
index 4080232..57c9256 100644
@@ -36,15 +36,6 @@ dependencies = [
]
[[package]]
name = "android_system_properties"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311"
dependencies = [
"libc",
]
[[package]]
name = "anyhow"
version = "1.0.102"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -382,19 +373,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "58b52a9840ffff5d4d0058ae529fa066a75e794e3125546acfc61c23ad755e49"
[[package]]
name = "chrono"
version = "0.4.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c673075a2e0e5f4a1dde27ce9dee1ea4558c7ffe648f576438a20ca1d2acc4b0"
dependencies = [
"iana-time-zone",
"js-sys",
"num-traits",
"wasm-bindgen",
"windows-link",
]
[[package]]
name = "ciborium"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -477,12 +455,6 @@ dependencies = [
]
[[package]]
name = "core-foundation-sys"
version = "0.8.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
[[package]]
name = "core2"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -577,27 +549,6 @@ dependencies = [
]
[[package]]
name = "dirs"
version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e"
dependencies = [
"dirs-sys",
]
[[package]]
name = "dirs-sys"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab"
dependencies = [
"libc",
"option-ext",
"redox_users",
"windows-sys 0.61.2",
]
[[package]]
name = "displaydoc"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -837,23 +788,12 @@ dependencies = [
]
[[package]]
name = "fontconfig-parser"
version = "0.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbc773e24e02d4ddd8395fd30dc147524273a83e54e0f312d986ea30de5f5646"
dependencies = [
"roxmltree",
]
[[package]]
name = "fontdb"
version = "0.23.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "457e789b3d1202543297a350643cf459f836cade38934e7a4cf6a39e7cde2905"
dependencies = [
"fontconfig-parser",
"log",
"memmap2",
"slotmap",
"tinyvec",
"ttf-parser",
@@ -909,17 +849,6 @@ dependencies = [
[[package]]
name = "getrandom"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
dependencies = [
"cfg-if",
"libc",
"wasi",
]
[[package]]
name = "getrandom"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
@@ -1219,30 +1148,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "74e25026c579b170c59f8d3ddfc523d7dab0abe079f09eb8edaebd2417044f60"
[[package]]
name = "iana-time-zone"
version = "0.1.65"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"
dependencies = [
"android_system_properties",
"core-foundation-sys",
"iana-time-zone-haiku",
"js-sys",
"log",
"wasm-bindgen",
"windows-core",
]
[[package]]
name = "iana-time-zone-haiku"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"
dependencies = [
"cc",
]
[[package]]
name = "icu_collections"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -1593,16 +1498,6 @@ dependencies = [
]
[[package]]
name = "js-sys"
version = "0.3.91"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b49715b7073f385ba4bc528e5747d02e66cb39c6146efb66b781f131f0fb399c"
dependencies = [
"once_cell",
"wasm-bindgen",
]
[[package]]
name = "kamadak-exif"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -1668,15 +1563,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
[[package]]
name = "libredox"
version = "0.1.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1744e39d1d6a9948f4f388969627434e31128196de472883b39f148769bfe30a"
dependencies = [
"libc",
]
[[package]]
name = "linked-hash-map"
version = "0.5.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -1760,15 +1646,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"
[[package]]
name = "memmap2"
version = "0.9.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "714098028fe011992e1c3962653c96b2d578c4b4bce9036e15ff220319b1e0e3"
dependencies = [
"libc",
]
[[package]]
name = "mime"
version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -1920,12 +1797,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "option-ext"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
[[package]]
name = "palette"
version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -2503,7 +2374,6 @@ dependencies = [
"tonic-prost",
"tonic-prost-build",
"typst",
"typst-as-lib",
"typst-render",
]
@@ -2517,17 +2387,6 @@ dependencies = [
]
[[package]]
name = "redox_users"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac"
dependencies = [
"getrandom 0.2.17",
"libredox",
"thiserror",
]
[[package]]
name = "regex"
version = "1.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -3351,21 +3210,6 @@ dependencies = [
]
[[package]]
name = "typst-as-lib"
version = "0.15.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c5d1310816d33fa3582dbb60bf0e5272af44d955a5fa13b148ddea62005088df"
dependencies = [
"chrono",
"comemo",
"dirs",
"ecow",
"thiserror",
"typst",
"typst-kit",
]
[[package]]
name = "typst-assets"
version = "0.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -3413,23 +3257,6 @@ dependencies = [
]
[[package]]
name = "typst-kit"
version = "0.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "31476ec753e080ffdd543a0e74b6d319355449ff3eca3f216634f31cfd09a92a"
dependencies = [
"ecow",
"fontdb",
"once_cell",
"serde",
"serde_json",
"typst-library",
"typst-syntax",
"typst-timing",
"typst-utils",
]
[[package]]
name = "typst-layout"
version = "0.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -4028,65 +3855,12 @@ dependencies = [
]
[[package]]
name = "windows-core"
version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
dependencies = [
"windows-implement",
"windows-interface",
"windows-link",
"windows-result",
"windows-strings",
]
[[package]]
name = "windows-implement"
version = "0.60.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "windows-interface"
version = "0.59.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-result"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
dependencies = [
"windows-link",
]
[[package]]
name = "windows-strings"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
dependencies = [
"windows-link",
]
[[package]]
name = "windows-sys"
version = "0.59.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
Cargo.toml +0 -1
diff --git a/Cargo.toml b/Cargo.toml
index d78ed73..3e9bad7 100644
@@ -11,7 +11,6 @@ tokio = { version = "1.50.0", features = ["rt-multi-thread", "macros"] }
tonic = "0.14.5"
tonic-prost = "0.14.5"
typst = "0.14.2"
typst-as-lib = { version = "0.15.4", features = ["typst-kit-fonts"] }
typst-render = "0.14.2"
[build-dependencies]
assets/CascadiaCode-Regular.ttf +0 -0
diff --git a/assets/CascadiaCode-Regular.ttf b/assets/CascadiaCode-Regular.ttf
new file mode 100644
index 0000000..98d489c
Binary files /dev/null and b/assets/CascadiaCode-Regular.ttf differ
assets/CascadiaCode.license +94 -0
diff --git a/assets/CascadiaCode.license b/assets/CascadiaCode.license
new file mode 100644
index 0000000..40f856f
@@ -0,0 +1,94 @@
Copyright (c) 2019 - Present, Microsoft Corporation,
with Reserved Font Name Cascadia Code.
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
assets/LibreBaskerville-Regular.ttf +0 -0
diff --git a/assets/LibreBaskerville-Regular.ttf b/assets/LibreBaskerville-Regular.ttf
new file mode 100644
index 0000000..5a16e76
Binary files /dev/null and b/assets/LibreBaskerville-Regular.ttf differ
assets/LibreBaskerville.license +94 -0
diff --git a/assets/LibreBaskerville.license b/assets/LibreBaskerville.license
new file mode 100644
index 0000000..82edbc0
@@ -0,0 +1,94 @@
Copyright (c) 2012, Pablo Impallari (www.impallari.com|impallari@gmail.com),
Copyright (c) 2012, Rodrigo Fuenzalida (www.rfuenzalida.com|hello�rfuenzalida.com), with Reserved Font Name Libre Baskerville.
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
assets/template.typ +2 -1
diff --git a/assets/template.typ b/assets/template.typ
index ddbafad..ed157ac 100644
@@ -4,6 +4,7 @@
margin: (y: 0.1cm, x: 0.05cm),
fill: none,
)
#set text(font: "Times New Roman")
#set text(font: "Libre Baskerville")
#show raw: set text(font: "Cascadia Code")
#eval(mode: "markup", sys.inputs.content)
src/main.rs +3 -5
diff --git a/src/main.rs b/src/main.rs
index a3167de..d8e1a53 100644
@@ -13,8 +13,8 @@ use crate::receipt_printer_service::ReceiptPrinterService;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<_> = args().skip(1).collect();
if args.len() != 2 {
println!("Please provide the printer connection string and .typ template as arguments");
if args.len() != 1 {
println!("Please provide the printer connection string as arguments");
return Ok(());
};
let Some((printer_host, printer_port)) = args[0]
@@ -24,12 +24,10 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("Printer connection string must be on format `host:port`");
return Ok(());
};
let template_path = &args[1];
let receipt_printer = ReceiptPrinter::init(printer_host.to_owned(), printer_port);
let receipt_printer_service =
ReceiptPrinterService::new(template_path.to_owned(), receipt_printer);
let receipt_printer_service = ReceiptPrinterService::new(receipt_printer);
Server::builder()
.add_service(ReceiptPrinterServer::new(receipt_printer_service))
src/receipt_printer_service.rs +3 -7
diff --git a/src/receipt_printer_service.rs b/src/receipt_printer_service.rs
index f1b2bed..766f103 100644
@@ -7,16 +7,12 @@ use crate::receipt_printer::ReceiptPrinter;
use crate::typst_renderer::render_typst_receipt;
pub struct ReceiptPrinterService {
template_path: String,
receipt_printer: ReceiptPrinter,
}
impl ReceiptPrinterService {
pub fn new(template_path: String, receipt_printer: ReceiptPrinter) -> Self {
Self {
template_path,
receipt_printer,
}
pub fn new(receipt_printer: ReceiptPrinter) -> Self {
Self { receipt_printer }
}
}
@@ -33,7 +29,7 @@ impl receipt_printer_server::ReceiptPrinter for ReceiptPrinterService {
return Err(Status::invalid_argument("No Typst content received"));
};
let image = match render_typst_receipt(self.template_path.as_ref(), content) {
let image = match render_typst_receipt(content) {
Ok(image) => image,
Err(error) => {
return Err(Status::internal(format!(
src/typst_renderer/mod.rs +17 -23
diff --git a/src/typst_renderer.rs b/src/typst_renderer/mod.rs
similarity index 60%
rename from src/typst_renderer.rs
rename to src/typst_renderer/mod.rs
index 72df7aa..9655330 100644
@@ -1,27 +1,16 @@
mod receipt_world;
use std::fmt::Display;
use png::EncodingError;
use typst::{
foundations::{Dict, IntoValue},
layout::PagedDocument,
};
use typst_as_lib::{TypstAsLibError, TypstEngine, typst_kit_options::TypstKitFontOptions};
use crate::receipt_printer::ReceiptPrinter;
pub fn render_typst_receipt(
template_path: &str,
content: &str,
) -> Result<Vec<u8>, TypstRenderError> {
let engine = TypstEngine::builder()
.with_file_system_resolver(".")
.search_fonts_with(TypstKitFontOptions::new().include_system_fonts(true))
.build();
let mut inputs = Dict::new();
inputs.insert("content".into(), content.into_value());
let document: PagedDocument = engine
.compile_with_input(template_path, inputs)
use typst::{diag::SourceDiagnostic, ecow::EcoVec, layout::PagedDocument};
use self::receipt_world::ReceiptWorld;
use super::receipt_printer::ReceiptPrinter;
pub fn render_typst_receipt(content: &str) -> Result<Vec<u8>, TypstRenderError> {
let world = ReceiptWorld::new(content);
let document: PagedDocument = typst::compile(&world)
.output
.map_err(TypstRenderError::Compilation)?;
@@ -39,7 +28,7 @@ pub fn render_typst_receipt(
#[derive(Debug)]
pub enum TypstRenderError {
Compilation(TypstAsLibError),
Compilation(EcoVec<SourceDiagnostic>),
NoOutput,
MultiPageOutput,
Rendering(EncodingError),
@@ -48,7 +37,12 @@ pub enum TypstRenderError {
impl Display for TypstRenderError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
TypstRenderError::Compilation(typst_as_lib_error) => typst_as_lib_error.fmt(f),
TypstRenderError::Compilation(diagnostics) => {
for diagnostic in diagnostics {
writeln!(f, "Compile: {}: {:?}", diagnostic.message, diagnostic.trace)?;
}
Ok(())
}
TypstRenderError::NoOutput => write!(f, "No output"),
TypstRenderError::MultiPageOutput => write!(f, "Multi-page output"),
TypstRenderError::Rendering(encoding_error) => encoding_error.fmt(f),
src/typst_renderer/receipt_world.rs +85 -0
diff --git a/src/typst_renderer/receipt_world.rs b/src/typst_renderer/receipt_world.rs
new file mode 100644
index 0000000..2de73b8
@@ -0,0 +1,85 @@
use std::{cell::LazyCell, sync::Arc};
use typst::{
Library, LibraryExt, World,
diag::{FileError, FileResult},
foundations::{Bytes, Datetime, Dict, IntoValue},
syntax::{FileId, Source},
text::{Font, FontBook},
utils::LazyHash,
};
const TEMPLATE_STRING: &str = include_str!("../../assets/template.typ");
const LIBREBASKERVILLE_REGULAR_BYTES: &[u8] =
include_bytes!("../../assets/LibreBaskerville-Regular.ttf");
const CASCADIACODE_REGULAR_BYTES: &[u8] = include_bytes!("../../assets/CascadiaCode-Regular.ttf");
thread_local! {
static TEMPLATE_SOURCE: LazyCell<Source> =
LazyCell::new(|| Source::detached(TEMPLATE_STRING));
static FONTS: LazyCell<(Arc<LazyHash<FontBook>>, Vec<Font>)> = LazyCell::new(|| {
let fonts = vec![
Font::new(Bytes::new(LIBREBASKERVILLE_REGULAR_BYTES), 0).unwrap(),
Font::new(Bytes::new(CASCADIACODE_REGULAR_BYTES), 0).unwrap(),
];
let font_book = Arc::new(LazyHash::new(FontBook::from_fonts(&fonts)));
(font_book, fonts)
});
}
pub struct ReceiptWorld {
library: LazyHash<Library>,
font_book: Arc<LazyHash<FontBook>>,
}
impl ReceiptWorld {
pub fn new(content: &str) -> Self {
let mut input = Dict::new();
input.insert("content".into(), content.into_value());
let font_book = FONTS.with(|fonts| fonts.0.clone());
Self {
library: LazyHash::new(Library::builder().with_inputs(input).build()),
font_book,
}
}
}
impl World for ReceiptWorld {
fn library(&self) -> &LazyHash<Library> {
&self.library
}
fn book(&self) -> &LazyHash<FontBook> {
&self.font_book
}
fn main(&self) -> FileId {
TEMPLATE_SOURCE.with(|source| source.id())
}
fn source(&self, id: FileId) -> FileResult<Source> {
if id == self.main() {
Ok(TEMPLATE_SOURCE.with(|source| (*source).clone()))
} else {
Err(FileError::NotFound(
id.vpath().as_rootless_path().to_path_buf(),
))
}
}
fn file(&self, id: FileId) -> FileResult<Bytes> {
Err(FileError::NotFound(
id.vpath().as_rootless_path().to_path_buf(),
))
}
fn font(&self, index: usize) -> Option<Font> {
FONTS.with(|fonts| fonts.1.get(index).cloned())
}
fn today(&self, _offset: Option<i64>) -> Option<Datetime> {
None
}
}