Typst is an application which is used for creating pdf and images from typst files. Typst has a custom templating syntax which it uses for constructing various page elements and it also has a scripting system much like a programming language which enables you to do some really cool stuff.
It’s written in rust which makes it quite performant and gives it some type safe guarantees.it has a packaging system which enables you to import other packages written by others into your typst project.it is also multiplatform as well.its similar to latex in what it does and its functionality.
First of all let’s create a new phoenix project to show its usage.This project will be a blog where we will have the ability to create,read,update,preview,download and delete blog posts.
First we create a new phoenix project
|
|
After creating the project,we need to have the typst executable in the priv folder of our phoenix app.We go to the typst github page and follow the instructions for installation.
After installation of typst, we get the executable and then place it in the priv folder.I usually create a priv/typst
folder and put the executable there.We also create two typst files and put them in the folder also.
One is an api file(main.typ
) and the other a template file(blog.typ
) which contains the blog typst code.Seperation of the api file and the template typst files enables the template to be used in other scenarios and enables seperation of concern also.
main.typ
|
|
blog.typ
|
|
We then run the generator for live view to generate some scaffolding and boilerplate code
|
|
We are now going to add some endpoints for the preview/downloading and also for the preview modal.
We add the following endpoints th the router.ex
.
|
|
the first link enables you to process a blog based on the id
and the type
.the type
can be either view or download and enables you to view and download the pdf respectivity.
the second link enables you to preview the pdf in a modal.
We create an action in TypstAppWeb.PostLive.Index
to process the preview
action.
|
|
We add a function process_blog
in TypstAppWeb.PageController
to enable us to get the blog information,encode to json which is acceptable to typst,shell out and execute the typst command for creating the pdf/png output file and send the generated file to the client.In my case i used the png for the preview and the pdf for the download option.
|
|
We edit the index.html.heex
file and add links after the edit link for previewing as well as downloading the blog as well.one is a patch and one is a normal href link. .
|
|
We also add a modal component to index.html.heex
to enable you to create a preview modal.
|
|
Thats it.This has been interesting.
Typst is an easy and useful tool for generating pdfs in elixir apps. I imagine it being used in conjuction with oban for generating receipts,invoices and other attachments. So have fun with it and you can also find the link to this example repo here also.