84

How should I incorporate TeX in a website to render mathematical formulas? If there are multiple ways, what is the easiest way?

7
  • 3
    For WordPress blogs have a look at QuickLaTeX. It seems also support other forms of online sites. Commented Jul 22, 2011 at 12:45
  • Exactly duplicate How to use Latex on blogspot? Commented Jul 22, 2011 at 12:55
  • To give a good answer, we really need to know more about your setup. How do you want to generate the webpages? What are your priorities in getting the mathematics on the web (accessible? All browsers? Styleable?)? Commented Jul 22, 2011 at 13:02
  • 9
    @xport: Not really. There's a difference between blogspot (i.e. no access to the server in any way) and general websites (i.e. possibly ftp/ssh or even physical access to the server).
    – You
    Commented Jul 22, 2011 at 13:03
  • @You: OK. But installing CDN MathJax is allowed in blogspot without needing special administrative credential. Or she/he wants to install his/own server scripts to produce PDF output from TeX input files. Commented Jul 22, 2011 at 14:00

10 Answers 10

47

To display mathematics on the web, you have a number of options. There is the MathML standard which has the advantage of being endorsed by the same body that maintains the HTML and CSS standards. This isn't however, LaTeX based. There are tools to translate LaTeX code into MathML.

There is the "heavy duty" MathJax option. You can either install this on your server or use their CDN.

The simplest approach might be to use something like codecogs to produce images that you just include with html img tags...

2
  • Using CDN does simply your server settings as well where you don't need to setup MIME for fonts used in the MathJax library. Commented Jul 22, 2011 at 13:09
  • 1
    Unfortunately, the MathML standard is really only recommended by the W3C, and is only supported in Firefox and newer versions of Safari (see developer.mozilla.org/en-US/docs/Web/MathML/Element/…)
    – Jack
    Commented Oct 1, 2016 at 1:37
37

here you find an example for MathJaX:

http://latex.userpage.fu-berlin.de/math.html

the source code:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<title>Mathedemo</title>
<script type="text/x-mathjax-config">
  MathJax.Hub.Config({tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}});
</script>
<script type="text/javascript"
  src="http://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
</head>

<body>
<h2>Math in TeX notation</h2>

When $a \ne 0$, there are two solutions to \(ax^2 + bx + c = 0\) and they are
$$x = {-b \pm \sqrt{b^2-4ac} \over 2a}.$$
$$ \begin{array}{rcll}
y & = & x^{2}+bx+c\\
  & = & x^{2}+2\times\dfrac{b}{2}x+c\\
  & = & \underbrace{x^{2}+2\times\dfrac{b}{2}x+\left(\frac{b}{2}\right)^{2}}-
      {\left(\dfrac{b}{2}\right)^{2}+c}\\
  &  & \qquad\left(x+{\dfrac{b}{2}}\right)^{2}\\
  & = & \left(x+\dfrac{b}{2}\right)^{2}-\left(\dfrac{b}{2}\right)^{2}+c 
  & \left|+\left({\dfrac{b}{2}}\right)^{2}-c\right.\\
    y+\left(\dfrac{b}{2}\right)^{2}-c & = & \left(x+
    \dfrac{b}{2}\right)^{2} & \left|\strut(\textrm{vertex form})\right.\\
y-y_{S} & = & (x-x_{S})^{2}\\
S(x_{S};y_{S}) & \,\textrm{or}\, 
    & S\left(-\dfrac{b}{2};\,\left(\dfrac{b}{2}\right)^{2}-c\right)
\end{array} $$

<h2>Math in MathML notation</h2>

When <math><mi>a</mi><mo>&#x2260;</mo><mn>0</mn></math>,
there are two solutions to <math>
  <mi>a</mi><msup><mi>x</mi><mn>2</mn></msup>
  <mo>+</mo> <mi>b</mi><mi>x</mi>
  <mo>+</mo> <mi>c</mi> <mo>=</mo> <mn>0</mn>
</math> and they are
<math mode="display">
  <mi>x</mi> <mo>=</mo>
  <mrow>
    <mfrac>
      <mrow>
        <mo>&#x2212;</mo>
        <mi>b</mi>
        <mo>&#x00B1;</mo>
        <msqrt>
          <msup><mi>b</mi><mn>2</mn></msup>
          <mo>&#x2212;</mo>
          <mn>4</mn><mi>a</mi><mi>c</mi>
        </msqrt>
      </mrow>
      <mrow> <mn>2</mn><mi>a</mi> </mrow>
    </mfrac>
  </mrow>
  <mtext>.</mtext>
</math>
</body>
</html>
2
  • Unfortunately, \cancel, \bcancel, etc don't exist in MathJax. :-( Commented Jul 22, 2011 at 13:05
  • 7
    there are no such commands in the default math mode
    – user2478
    Commented Jul 22, 2011 at 13:07
8

I'll add two math rendering alternatives only for reference purposes. Personally, I prefer to stick with either MathML or MathJaX.

Both MimeTeX and MathTeX are cgi programs written in C.

MimeTeX

MimeTeX, licensed under the gpl, lets you easily embed LaTeX math in your html pages. It parses a LaTeX math expression and immediately emits the corresponding gif image, rather than the usual TeX dvi. And mimeTeX is an entirely separate little program that doesn't use TeX or its fonts in any way. It's just one cgi that you put in your site's cgi-bin/ directory, with no other dependencies. So mimeTeX is very easy to install. And it's equally easy to use. Just place an html <img> tag in your document wherever you want to see the corresponding LaTeX expression. For example,

<img src="../cgi-bin/mimetex.cgi?f(x)=\int_{-\infty}^xe^{-t^2}dt"
 alt="" border=0 align=middle>

immediately generates the corresponding gif image on-the-fly, displaying wherever you put that <img> tag. MimeTeX doesn't need intermediate dvi-to-gif conversion, and doesn't create separate gif files for each converted expression. (But you can cache images with mimeTeX's -DCACHEPATH=\"path/\" compile option.)

MathTeX

MathTeX, licensed under the gpl, is a cgi program that lets you easily embed LaTeX math in your own html pages, blogs, wikis, etc. It parses a LaTeX math expression and immediately emits the corresponding gif (or png) image, rather than the usual TeX dvi. So just place an html <img> tag in your document wherever you want to see the corresponding LaTeX expression. For example,

<img src="/cgi-bin/mathtex.cgi?f(x)=\int_{-\infty}^xe^{-t^2}dt"
 alt="" border=0 align="middle">

immediately generates the corresponding gif, displaying wherever you put that <img> tag.

mathTeX dependencies

MathTeX's uses the latex and dvipng programs, along with all necessary fonts, etc, from your TeX distribution. Occasionally, you may need to download dvipng separately. If you can't, or don't want to, install dvipng, then you may optionally specify the –DDVIPS and –DCONVERT switches when compiling mathTeX. Then mathTeX uses dvips from your TeX distribution, and convert from the ImageMagick package, instead of dvipng.

[...]

These dependencies - always latex and either dvipng or dvips/convert - must all be installed on your server before you can run mathTeX. Ask your ISP or sysadmin if you have any questions or problems installing them. Or see mimeTeX if you can't install them.

7
  1. If you just want to render LaTeX commands as HTML output, then Herbert's answer is the correct way to go, i.e., using MathJax library provided by some CDN. Using CDN is very useful since you don't need to host MathJax library by yourself, you don't need to update MathJax library, you don't need to setup MIME on your server to allow MathJax fonts passing through the web server pipeline, etc.
  2. But if you want to render LaTeX commands as PDF output, then MathJax will not help you! Depending on the content, whether you use EPS, JPEG, PNG, PDF in you LaTeX input file, you need to setup a server script to execute latex.exe or pdflatex.exe and other tools to get PDF output. This workflow is not for a newbie because you have to know a programming language for writing server script. If you are a C# user and know ASP.NET MVC, the following incomplete code snippet may help you to get the rough idea. But it has not been optimized and analyzed for any security vulnerability.
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = "Administrators")]
public ActionResult Create(Problem problem )
{
    ViewBag.Message = "LaTeX to PDF Converter";

    string dir = Server.MapPath("~/Content/");
    name = Path.GetRandomFileName() + MvcApplication.rnd.Next(int.MaxValue);
    string inputpath = Path.Combine(dir, name + ".tex");

    using (StreamWriter sw = new StreamWriter(inputpath))
    {
        sw.Write(problem.Description);
    }


    Process p = new Process();

    p.EnableRaisingEvents = true;
    p.Exited += new EventHandler(p_Exited);

    p.StartInfo.Arguments = "-interaction=nonstopmode " + inputpath;
    p.StartInfo.WorkingDirectory = dir;

    p.StartInfo.UseShellExecute = false;
    p.StartInfo.FileName = "pdflatex.exe";

    p.Start();
    p.WaitForExit();

    if (p.ExitCode == 0)
    {

        TempData["outputpath"] = Url.Content("~/Content/" + name + ".pdf");


        return RedirectToAction("Result");
    }
    else
    {
        ModelState.AddModelError("Description", "Syntax Error!");
        return View(problem);
    }
}

void p_Exited(object sender, EventArgs e)
{
    Process p = sender as Process;
    string dir = Server.MapPath("~/Content/");
    using (StreamWriter sw = new StreamWriter(Path.Combine(dir, "log.txt"), true))
    {
        sw.WriteLine(DateTime.Now);
    }

    var filenames = Directory.GetFiles(dir, name + "*");
    for (int x = 0; x < filenames.Length; x++)
    {
        if (Path.GetExtension(filenames[x]) != ".pdf" || p.ExitCode != 0)
            System.IO.File.Delete(filenames[x]);
    }

}

You need to create a separate process to invoke pdflatex to compile the input file.

4

KaTeX

I would also highly recommend looking into https://katex.org/

It is a much like MathJax, but it has one fundamental amazing feature: server-side rendering. Maybe MathJax 3 implemented it: http://docs.mathjax.org/en/v3.2-latest/upgrading/whats-new-3.0.html#server-side-mathjax but not sure.

With this, you can render the formulas fully as HTML elements like div and span on the server, and then those will be rendered correctly on the browser using only the corresponding CSS.

This is unlike MathJax (pre 3.0 for sure) which as far as I've seen renders on browser only, so users might end up seeing their LaTeX formulas expand to rendered strings. It can also mean page reflowing if heights are altered from the LaTeX input to the rendered output.

All you have to do is:

katex.renderToString('\\frac{1}{\\sqrt{2}}')

and then add that string to the document and include the CSS:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.13.11/katex.min.css" integrity="sha512-J8je2SgrCzA7hNBeiCJiA6oETHTTdp3We3EriOgJp6POycGLcDXj5dSwWlAPQcYGeaQ4N3uf30aOg/Nt5pxW2g==" crossorigin="anonymous" referrerpolicy="no-referrer" />

Here's a minimal example. It is not strictly server-side, but it could be obviously made so easily by calling katex.renderToString on your Node.js server when rendering the page, I'm using that daily now so I'm sure it works:

<!doctype html>
<html lang=en>
<head>
<meta charset=utf-8>
<title>Client-side KaTeX</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.13.11/katex.min.js" integrity="sha512-1kNZVA50gKlorLAWU83+SdOAUwABzfFFQ4WuOAZTeS/UhNhnm9zU7rDv/Q5NEzSnr5u2L6uhR/+8icjjmHjSnQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.13.11/katex.min.css" integrity="sha512-J8je2SgrCzA7hNBeiCJiA6oETHTTdp3We3EriOgJp6POycGLcDXj5dSwWlAPQcYGeaQ4N3uf30aOg/Nt5pxW2g==" crossorigin="anonymous" referrerpolicy="no-referrer" />
</head>
<body>
</body>
<script>
document.getElementsByTagName('body')[0].innerHTML = katex.renderToString('\\frac{1}{\\sqrt{2}}')
</script>
</html>
2

There is also the possibility to use LateXMathML, which converts LaTeX Math Mode to MathML with JavaScript only. No serverside installation needed.

1

Since HTML does not support embedded LaTeX, converting the LaTeX to MathML for use with MathJax is an acceptable means, however the problem then becomes one of converting the LaTeX to MathML and seamlessly converting the MathML for use by the HTML browser.

  1. The translation of LaTeX to MathML for use by MathJax can be done using the online WIRIS editor.

    a. Just past the LaTeX in the LaTeX window and click apply.
    b. Then copy the converted MathML from the MathML window into the HTML.

  2. The MathML can then be seamlessly converted for use by the browser by use of the MathJax service with the adding of the following script to the HTML head.

<head>
    <script type="text/javascript"
            src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_SVG">
    </script>
</head>

TL;DR

The WIRIS editor is also know as a formula editor or equation editor.

Note that the WIRIS editor can also do

  • MathML to LaTeX
  • linear text to MathML
  • linear text to LaTeX
1
0

The free and open source Foswiki platform have a LatexModePlugin that allow insert easily chunks of LaTeX code within the wiki text, that are rendered as .png or .gif images. How it work is well explained in the above link.

There are also a MathModePlugin but as the name suggest only implement rendering images of mathematics formulas.

0

I had a good experience with pandoc,

$ pandoc file.tex --standalone --mathjax --output file.html

Then, you upload this file.html to the web.

0

I am very much not an expert here, but I have found a way that seems to work. In the <head> section of my html file, include:

<head> <script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script> </head

then you can simply write latex (\mathbb{Z}) as you wish. Note, this was suggested by ChatGPT.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .