Creating PDF with JavaScript
Categories: Development, boxes and glue
I have created JavaScript bindings for boxes and glue. These bindings are made with goja. Let me show you an example:
const bag = require("bag:backend/bag")
const fe = require("bag:frontend")
const f = fe.new("out.pdf")
const str = `In olden times when wishing still helped one,
there lived a king whose daughters were all beautiful;
and the youngest was so beautiful that the sun itself,
which has seen so much, was astonished whenever it shone
in her face. Close by the king’s castle lay a great dark
forest, and under an old lime-tree in the forest was a well,
and when the day was very warm, the king’s child went out
into the forest and sat down by the side of the cool
fountain; and when she was bored she took a golden ball,
and threw it up on high and caught it; and this ball was her
favorite plaything.`.replace(/\s+/g, ' ').trim()
const fontsource = new fe.fontSource(
{ location: "CrimsonPro-Regular.ttf"}
);
const ff = f.newFontFamily("text");
ff.addMember(fontsource, fe.fontWeight400, fe.fontStyleNormal);
const para = fe.newText();
para.settings[fe.settingSize] = 12 * bag.factor;
para.items.push(str);
const ret = f.formatParagraph(
para,
bag.mustSP("125pt"),
fe.leading(14 * bag.factor),
fe.family(ff));
const p = f.doc.newPage();
p.outputAt(bag.mustSP("1cm"), bag.mustSP("26cm"), ret[0]);
p.shipout();
f.doc.finish();
Which look familiar when you know at the “getting started” document in the manual.
Tun run the JavaScript file above, you need to download the software ets (see the Readme file in the repository), download the font and run
ets myfile.js
on the command line.
This produces two files (hopefully): a PDF file (out.pdf
in this case) and a log file (ets-protocol.xml
) which contains information about errors and warning, in case something goes wrong.
The JavaScript bindings are documented at boxesandglue.dev/ets/. Examples are found in a repository.
Currently ets is at version 0.0.2, you can conclude from that version number that this is still in the beginning of development. My next steps are including input and output of regular files, a JSON and XML reader as well as http-bindings to access assets without download.