Ben Borgers

How to render LaTeX to HTML with Node.js

December 5, 2020

To render LaTeX as HTML, we're going to be using the KaTeX npm package. First, install it:

npm install katex

Now, to render a string of LaTeX into HTML, we can use that package:

const katex = require('katex')

const latexString = 'e = mc^2'

const html = katex.renderToString(latexString)

Now, html will be a rendering of the LaTeX in HTML. To make it show properly, you'll need to include KaTeX's special CSS file, which styles the outputted HTML with the correct fonts and positioning. Drop this CSS file into the <head> of your HTML file along with the rendered LaTeX:

<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/katex.min.css" />

Now, opening the HTML file containing the rendered LaTeX-as-HTML string and that linked CSS file will show the LaTeX beautifully rendered.

More blog posts

Subscribe to my newsletter for a monthly round-up of new blog posts and projects Iā€™m working on!

Twitter ↗ RSS feed ↗