I would like to use Typst to create small images for a eink screen I have. I am thinking using Rust templating strings to create the Typst code and then compiling it to PNG then BMP.
I have had a play with typst-as-lib but it seems a bit overkill and can’t seem to get it to work.
I just need to pass in a Typst string into the compiler, load system fonts and then spit out a png buffer, any help would be much appreciated!
A better approach would be to write a Typst template, and then populate it using Typst’s data loading capabilities. See e.g. here for a discussion (including embedding this in a Python script.
If you have specific questions, we can try to help. But it might be easier to call the Typst compiler executable instead of the library, depending on what the environment you’re running in is like.
Interestingly, this came up in a podcast recently. The co-host who talked about it is James Munns. I didn’t find find anything on his Github, but maybe that pointer turns out useful.
(PS: your combination of profile picture and user name is great
)
I’ll give that a try, thanks!
Yeah, from what I’ve seen online a lot of setup is required to use Typst as a library and actually didn’t think about calling the binary itself directly - so I’ll try that.
I am going to be running in a Raspberry Pi Zero 2 W, so it shouldn’t be too much of a constraint.
I was originally planning to use HTML and then call Chromium functions to render the webpage as an image, but that was going to be a little too extreme for the Pi and I have more experience with Latex anyway.
I saw that as well! That’s what inspired me to check out Typst, and I must say I’m loving it so far.
;)
1 Like
If anyone is wondering how to do this, I just called the Typst binary with the Rust code passing in the template as stdin
and then handling the result on stdout
— it could probably be optimised more – but it works:
use std::io::{self, Write};
use std::process::{Command, Stdio};
use std::thread;
fn main() -> io::Result<()> {
let typst_string = r#"
= Hello from Rust! 🦀
Random equation,
$ attach(
Pi, t: alpha, b: beta,
tl: 1, tr: 2+3, bl: 4+5, br: 6,
) $
"#
.to_string();
let mut cmd = Command::new("typst")
.args(["compile", "-", "-", "--format", "png"])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()?;
let mut stdin = cmd.stdin.take().expect("Failed to open stdin");
thread::spawn(move || {
stdin
.write_all(typst_string.as_bytes())
.expect("Failed to write to stdin");
});
let output = cmd.wait_with_output()?;
if output.status.success() {
std::fs::write("output.png", &output.stdout)?;
} else {
let error_message = String::from_utf8_lossy(&output.stderr);
}
Ok(())
}
I’m going to have a play with Typst templates now :)
1 Like