Search code examples
javascripthtmlcssmathjax

Export HTML containing MathJax results


I use QWebEngineView to convert Markdown to HTML and render the math formula via MathJax. All the content are inside a <div id="placeholder">. Then I use document.getElementById("placeholder").innerHTML to get the HTML content, which contains the converted Markdown content and rendered MathJax output. At last, I output the HTML content to a HTML file.

However, when I open the exported HTML file via Chrome, the formulas lose the CSS styles like this demo.

So any idea to make the formulas in order?

I have tried to add MathJax script to the exported HTML but the formulas will disappear.

Thanks!


Solution

  • You need to grab not only the HTML, but also the CSS that MathJax's CommonHTML output jax produces, and the styles for the AssistiveMML extension (since your copied HTML includes its output as well). The code below will obtain it for you.

    <script type="text/x-mathjax-config">
    MathJax.Hub.Queue(function () {
      var styles = document.head.getElementsByTagName("style");
      styles = [].slice.call(styles); // convert to array
      while (styles.length) {
        var sheet = styles.pop();
        if (sheet.innerHTML.match(/^(?:.mjx-chtml|.MJX_Assistive_MathML) \{/)) {
          document.getElementById("sheet").innerHTML += sheet.innerHTML;
        }
      }
    });
    MathJax.Hub.Queue(function () {
      var math = document.getElementById("math");
      math.parentNode.removeChild(math);
    });
    </script>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.3/MathJax.js?config=TeX-AMS_CHTML"></script>
    
    <span id="math">\(x\)</span>
    
    <pre id="sheet">
    </pre>

    Put this into a .css file an link that to your page (or put it into a <style> tag in the document head). That should do it for you.