LaTeX Equations and Graphics in PHP

Make the difficulties of displaying mathematical equations on the Web a thing of the past by embedding LaTeX content in your pages.

It's safe to say that the world of Weblogs and wiki Web sites are here to stay. Although such systems are great for journals, general text posting and even photography, their limitations become apparent when working in environments that require the use of features more advanced than simple text entry and images. In particular, technical Weblogs need support for graphs, mathematical expressions, diagrams and more. Such functionality is difficult, if not impossible, to implement with HTML alone.

Using external applications such as dia, xfig and Microsoft Equation Editor is equally difficult, as the poster first must create the figure or mathematical equation and then upload an image representation to a Web site. Moreover, if other posters in a collaborative Weblog want to modify the figure, they also must possess the application as well as the original file that created the image. Obviously, this sort of system has its share of complications, and it fragments the overall quality of figures and equations for a site.

In this article, I demonstrate the use of LaTeX, a typesetting tool and language designed specifically for technical document preparation, from within PHP to address these demands. I call LaTeX from within PHP when HTML is not sufficient to address these complex needs and then render the result uniformly as a PNG image, a format all modern browsers support. Because the software is available entirely on the server, all posters and users have access to the same set of tools and packages for publication.

Requirements

Following the UNIX philosophy to “write programs to work together”, I use a composition of common tools available for the Linux platform and chain them together to produce a PNG-equivalent rendering of the LaTeX source. Specifically, you need a recent version of LaTeX with dvips and the ImageMagick toolkit. You are going to use the convert utility from the ImageMagick tools to convert your result into a PNG image. Luckily, most hosting providers that provide shell access already have these utilities available.

Project Overview

The rendering system takes a string of text and extracts segments enclosed in [tex] and [/tex] pairs for future substitution. These extracted segments are called thunks. If a thunk previously has been processed, meaning an image representation of the thunk code already is available, the thunk is replaced with a URL to that image. If the thunk is new, it is passed to the LaTeX typesetter, which outputs its result as a DVI file. The DVI file then is converted to a PNG image with ImageMagick and placed into the cache directory. A URL of the newly created image is substituted for the thunk in the original text. When all thunks have been processed, the resulting text is returned to the caller. The process for converting a single thunk is illustrated in Figure 1.

Figure 1. A Flowchart of the Rendering Process for a Single Thunk

Usage

I think it is best to start top-down and first look at how to invoke the rendering process, without discussing implementation specifications. The driver is simply an HTML front end that provides a mechanism for testing the LaTeX rendering system. It allows you to see how the render class should be invoked. To get you started, I've provided the basic template shown in Listing 1.

______________________

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Another aproach to LaTeX equations with PHP

Filipi Vianna's picture

Some time ago I had faced the same problem, but I didn't use the same rendering steps. Instead of rendering to PS and then converting to PNG, I had used dvipng to convert the DVI directly to PNG.

The code is at my personal blog.

Hope it also helps somebody.

Regards,
Filipi Vianna

A bit of trouble

Skylar Saveland's picture

I have been looking for something like this off and on for months but I am a programming newb with most experience in python; this article has me crash-coursing php.

I think I am having problems naming the .php files, placing them in the right place and/or setting the correct permissions. I know exactly where convert, latex and dvips are, that is not the problem. I have put everything in the document root in separate files, each listing.

wrap.php7870l3.qrk I have just named wrap.php, I can't find any logic for the '7870l3.qrk' part.

If I name the second listing/file 'render.php' I get the follwing error:
Warning: require(render.class.php) [function.require]: failed to open stream: No such file or directory in /var/www/render_example.php on line 26

Fatal error: require() [function.require]: Failed opening required 'render.class.php' (include_path='.:/usr/share/php:/usr/share/pear') in /var/www/render_example.php on line 26

If I name the second listing 'render.class.php' I get a different error:
class render { var $LATEX_PATH = "/usr/bin/latex"; var $DVIPS_PATH = "/usr/bin/dvips"; var $CONVERT_PATH = "/usr/bin/convert"; var $TMP_DIR = "/usr/home/biouser/texwebtmp"; var $CACHE_DIR = "/usr/home/biouser/texwebtmp/cache"; var $URL_PATH = "http://127.0.1.1/lj/cache"; function wrap($text) { ... } function transform($text) { ... } function render_latex($text) { ... } }
Fatal error: Class 'render' not found in /var/www/render_example.php on line 33

Something is going on here... I would b so excited and grateful if i could get this to work!!!

uninformed question

matt's picture

This looks exactly like what I need. I am trying to set up a simple wiki to collaborate with co-writers, and am trying to find how to embed latex capabilities. I am a rookie in programming though, and cannot figure out some things. Specifically, "You need to let PHP know where your tools are located and provide a directory where PHP can write temporary files and store its cache."==> What tools? I see I need latex and dvips etc., but what exactly are these as tools? I use latex, but don't know exactly what I need to upload to the server.

Thanks!
matt

Awesome!

David Sankey's picture

Hi!

I'm starting to implement this into a math worksheet website I'm (slowly) building. It's superior to html formatting because it doesn't vary from browser to browser. I had to alter it a bit because I'm making worksheets for print and the images weren't printing well. I changed the density to 300. Then, I get the image height using "identity" and reduce it by 40% using the height attribute in the image tag.

The images on screen are a bit choppy but the prints look great. My students are sure to appreciate it!

Would you like me to post a link or give you other credit?

Thanks a bunch!

Dynamic Base URL

Carlos S.'s picture

It may be a good idea to add a function to get the base URL instead of hard writing it on the source code.
it may be something like:

$base_url = 'http' . (isset($_SERVER['HTTPS']) ? $_SERVER['HTTPS'] == 'on' ? 's' : '' : '');
$base_url .= '://' .$_SERVER['HTTP_HOST'];
if ($dir = trim(dirname($_SERVER['SCRIPT_NAME']), '\,/')) {
$base_url .= "/$dir";
}
$URL_PATH= $base_url . "/cache"

Carlos

Web CAS, another LaTeX+PHP on Apache

Anonymous's picture

Although I has not read the interesting article, a project of SourceForge, WMI (Web Mathematic Interactive, http://wmi.sf.net), may be the subject that readers are interested. WMI integrates almost the powerful CAS in Linux world, e.g. Maxima, Octave, Gnuplot and Maple etc. within LAMP envirnment. Don't forget to visit the official site.

Curious

summentier's picture

How did you know that the article was interesting if you hadn't read it? I did read it and it was great help!

White Paper
Linux Management with Red Hat Satellite: Measuring Business Impact and ROI

Linux has become a key foundation for supporting today's rapidly growing IT environments. Linux is being used to deploy business applications and databases, trading on its reputation as a low-cost operating environment. For many IT organizations, Linux is a mainstay for deploying Web servers and has evolved from handling basic file, print, and utility workloads to running mission-critical applications and databases, physically, virtually, and in the cloud. As Linux grows in importance in terms of value to the business, managing Linux environments to high standards of service quality — availability, security, and performance — becomes an essential requirement for business success.

Learn More

Sponsored by Red Hat

White Paper
Private PaaS for the Agile Enterprise

If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.

Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.

Learn More

Sponsored by ActiveState