PHP\LaTeX, LaTeX renderer

Overview

PHPLatex is quick and dirty PHP script that makes TeX rendering easier. It was initially made for latex.knobs-dials.com.

At the core it just invokes latex, dvips, and convert.
Since each such execution can take a few seconds, it caches the resulting images, which means that later requests for exactly the same TeX are served from files, making it low-cost (mostly a little IO) to leave the function call in the PHP, which should make both using TeX on a page and changing it later a low-brainer, and easy on your resources.

It does have a few requirements, though you'll likely meet all of those on modern *nix-with-tetex installations.
Aside from some details like that, and some initial setup -- and the fact it just is a bit of a hack -- it seems to work well enough.

Note that external invocation so is always potentially unsafe in an untrusted environment (the utilities will run as your webserver user).
For a safer but rather more restrictive variation, check the ocaml parser that mediawiki (as in wikipedia) uses.

Released under the GPL. Comments, praise, complaints, bugs, fixes and whatnot all encouraged. Contact address: scarfboy$\!\ @\!~$gmail.com

Ideas / requests for comments

As I don't consider this a very serious script and it currently fulfils my needs, I am not actively working on it. Nice feature suggestions are welcome, of course.

I am considerering having it always render higher resolutions to have images be sharper in printing, although I would have to test whether this can be done elegantly and check that nothing reacts weirdly (browsers, OS settings, etc.). If anyone has played with something like that, I welcome your notes.

I may have messed up the transparency for PNGs and the trimming for GIFs. I'll look at this some time.

Download and changelog

Examples

Basics

   <? print texify('wh^{e^{e^{e^{e^{e_{e_e}}}}}}'); ?>
   wh^{e^{e^{e^{e^{e_{e_e}}}}}}

Since you write inside PHP strings, backslashes are interpreted, so double them. Also, PHP wants to interpret dollar characters as $variables, so escape those too -- PHP doesn't seem to allow anything nicer for either of these cases.

  <?
     print texify("
       $$\\begin{align} 
         (a+b)^3 & = (a+b)^2(a+b)\\\\
                 & = (a^2+2ab+b^2)(a+b)\\\\
                 & = (a^3+2a^2b+ab^2) + (a^2b+2ab^2+b^3)\\\\
                 & = a^3+3a^2b+3ab^2+b^3
       \\end{align}$$
     "); ?>

        $$\begin{align} (a+b)^3 & = (a+b)^2(a+b)\\        & = (a^2+2ab+b^2)(a+b)\\        & = (a^3+2a^2b+ab^2) + (a^2b+2ab^2+b^3)\\        & = a^3+3a^2b+3ab^2+b^3\end{align} $$

TeX text in HTML text

...should work well enough for normal-sized text. Since PHPLatex 0.4 there is some simple logic (which needs more work) that considers ascenders, descenders and adjusts the resulting vertical image.

For example: Paraglider, ooo, o,o, text, Fuji dojo, (o-w), o\#3, some normal text, $\int{x}$ `$dx'$', w/o/o, mojo \{1,2,4\}, some more normal text, www, Jojo [brick] oo, katie80, Times in TeX, and this is normal text again.

Colors, Resolution

While you can use any coloring TeX you want, the texify() call specifically lets you set the text and background colors in RGB (uses the color package). The background color is also transparent in the PNG, so you can fade to various background colors if you want, for example

  <? print texify('$\sqrt{2}$', 90, 1.0,0.6,0.1, 1.0,1.0,1.0); ?>
  <? print texify('$\sqrt{2}$', 90, 1.0,0.6,0.1, 0.0,0.0,0.0); ?>
On white  $\sqrt{2}$$\sqrt{2}$
On dark gray:  $\sqrt{2}$$\sqrt{2}$



The 90 there is the rendering resolution; 90 is the default, and you can use no higher than 300, which helps avoid cases where the raster step takes unreasonable CPU and memory. (You could change that cap in the PHP, of course)

This is 300dpi: $\sqrt[q]{r}$

Tables, packages

The following uses pstricks and colortab, and demonstrates how to include packages:

  <? print texify("
  \\definecolor{lightergray}{gray}{.875}
  \\newcommand*\\lightergray{\\color{lightergray}}

  \\begin{tabular}{|lc|r|}
  \\hline
  \\LCC \gray & \lightgray & \lightergray \\\\
  rabbit & 12 & sold \\\\ 
  frog   & 3.5 & pending \\\\ \\ECC
  \\hline
  \\end{tabular}",
  90,
  0.0,0.0,0.0,
  1.0,1.0,1.0,
  "\\usepackage{pstricks,colortab}"); ?>

\definecolor{lightergray}{gray}{.875}\newcommand*\lightergray{\color{lightergray}}\begin{tabular}{|lc|r|}\hline\LCC \gray & \lightgray & \lightergray \\rabbit & 12 & sold \\ frog   & 3.5 & pending \\ \ECC\hline\end{tabular}

README

(...for the development version)

README for PHPLaTeX

Renders LaTeX into images by calling LaTeX itself from PHP.

Requirements
- PHP                                    (>=4.3.0, as it uses sha1())
- imagemagick                            (for convert)
- ghostscript, and TeX Live (or teTeX),  (for latex and dvips)
  - packages color, amsmath, amsfonts, amssymb, and the extarticle document class
    (and relatively recent versions of some) Some of those may not be in a base install



Setup/Installation
- Have the requirements installed
  - all assumed to be in /usr/bin. You can change the absolute paths to latex, dvips, and/or convert if necessary
- Put phplatex.php somewhere from which you can include it.
- In each directory you will be *calling* the script from, create subdirecties 'tmp' and 'images' 
  with write permissions for the effective user. It should be enough to do:
   mkdir tmp images; chown apache:apache tmp images
  (...whatever user/group applies to your system; may be apache, www-user, www-data, apache2, or such)
- You could make sure the images are serve with a far-future Expires (since they won't change)


Use
- Include the code through something like include('path/to/phplatex.php');
- texify(texstring, dpi, r,g,b, br,bg,bb, extraprelude);
  Only texstring is required
   You can use almost arbitrary TeX, including but not limited to '$math$' strings.
  This function will return an string containing <img src="...">,
   which you'll probably PHP-print into the document to show the image.
  Because of PHP, you'll need to double blackslashes, and escape dollar signs
  (see also the examples)
 
Maintenance
- You can empty the tmp directory at will (may sometimes have some leftovers)
- You can empty the img directory to clean up old images (and have the rest be regenerated next page request)


Features
- Caches generated images (based on document string) so asking for TeX that has already been generated is cheap
  (a filesystem check and read) so you can just leave texify() calls in your code.
- Tweakabe size. The default (90) is usually the same size as HTML text.
  Capped at 300 to avoid resource hogging
- Allows coloring of page background and default text color
  (default is black on white, specifically 0.,0.,0. on 1.,1.,1.)
- Allows inclusion of extra TeX packages (via extraprelude)
- Generates PNGs with transparency (note: consider antialiasing to that background)
- Relies on image trimming instead of trusting dvips' bounding box.
- TeX text used in HTML text should show up somewhat decently 
  (there is some logic looking at character descenders and using CSS lowering to compensate)


Caveats
- Probably won't work on safe-mode PHP (which is common on much of the cheap shared hosting)
- Initial generation takes a while, perhaps a second per image
  On pages with a lot of images you may hit the PHP time limit, 
  and you'll need a few refreshes before everything is built and cached.
- Fails when you include TeX that typesets as two pages or more (try \small)
  (for some reason I'm using landscape. Unless I remember why I'll be removing that,
   because that just makes things more likely to layout onto two pages)
- Image conversion fails for very large images  (hence the resolution cap; >300dpi causes easily causes this)


Arguables
- Uses \nonstopmode, meaning latex will fix errors it can, so you can get away with some bad TeX.
  But it'll guess, and since we delete the log you won't know what it did.
- You can use arbitrary TeX, which you can see as a feature and as a security issue.
  Know what this means - and use at your own risk.
  Mostly (like any other PHP script not running in safe mode), the processes can do everything 
  that the effective web server user can, so you should have secured your filesystem against that.
  (if you trust everyone on the server and don't let users input TeX, you're safe enough)
- Requires recent TeX version as it uses extarticle and includes color, amsmath, amsfont, and amssymb.
  This may be bothersome for things that aren't recent or not tetex / texlive
- On low resolutions, the (default) Computer Modern fonts don't render as well as, say, pslatex fonts 
  (Times, Helvatica, Courier), due to thickness and antialiasing, so change fontset to taste.
  Sharpening helps only a little, and can look worse when colours or shades are involved 
  (I tried convert -unsharp 1x1+1+0).