Paginating Math

Paged.js can work with other JavaScripts to extend the type of content you are trying to produce. Today we will look at a very simple use case: the addition of an external script transforming Math content.

A math paper may contain many mathematical equations that must be rendered correctly like this:

To do this with paged.js we can use MathJax, a JavaScript engine to display mathematics equations in browsers. It can translate expressions written in AsciiMath,  LaTeX or MathML.

To use Mathjax with paged.js, we need to run it before the content is fragmented into pages.

By default, paged.js will run as soon as the DOM is ready. However, you can add an async before function or return a promise to delay parsing the content until other libraries have finished with it.

    window.PagedConfig = {
        before: () => {
            return new Promise(resolve, reject) {
                var mjAPI = require("./lib/main.js");
            }
        },
        after: (flow) => { console.log("after", flow) },
    };

MathJax lets you add a function to their queue to run when all the typesetting has finished, rather than returning a promise. So we can disable the auto run of the previewer and call window.PagedPolyfill.preview(); when it has finished typesetting the math.

   window.PagedConfig = {
        auto: false
    };
    MathJax.Hub.Queue(function () {
      window.PagedPolyfill.preview();
    });

By using the first method with MathJax, it is very easy to transform HTML with math into a PDF. The below is an example of this done with a math paper.

The source code for this example is available on the paged media gitlab, in a repo with several other little experiments you can explore.