Category: Web
Author/Contact Info Don Armstrong
dondelelcaro
http://www.donarmstrong.com
Description: CGI script that is passed a line of latex code, and ouputs a png of the same. Usefull for inline math formulae. (I use it in my reference/notetaking web app which I will release eventually.)

Code like <IMG SRC="latexmath2png.pl?latex=\LaTeX\"> becomes (imagine latex output) LaTeX.

Requires tetex, and imagemagick. (On debian systems, apt-get install tetex-bin imagemagick.)

Heavily inspired by tex2im.
#! /usr/bin/perl -w
# Draws a png of a passed latex math code
# Released under the GNU Public License
# (c) 29, January 2001 by Don Armstrong

# Inspired by tex2im version 1.3


use strict;  # or die!

use CGI::Carp qw/fatalsToBrowser/;

use CGI;
use File::Temp qw/tempfile tempdir/;
use FileHandle;

my $q = new CGI;

#default values
my $default = { background => 'white',
                foreground => 'black',
                format => 'png',
                resolution => '150x150',
                latex => 'x_0^2+y_0^2=r_0^2'
              };

if (defined $q->param('format') and $q->param('format') =~ /^(\w+)$/) 
+{
  $default->{format} = $1;
}

if (defined $q->param('resolution') and $q->param('resolution') =~ /^(
+\d+x\d+)$/) {
  $default->{'resolution'} = $1;
}

foreach my $param_key ('background','foreground','latex') {
  my $param_value = $q->param($param_key);
  if (defined $param_value and $param_value =~/[\w\d]/) {
    $default->{$param_key} = $param_value;
  }
}

$default->{latex_shell} = << 'EOL';
\documentclass[12pt]{article}
\usepackage{color}
\pagestyle{empty}
\pagecolor{<background>}
\begin{document}
\begin{eqnarray*}
{\color{<foreground>}
<latex>
}\end{eqnarray*}
\end{document}
EOL


# Slap in the latex and defaults into the latex shell
$default->{latex_shell} =~ s/\<(foreground|background|latex)\>/$defaul
+t->{$1}/ge;

# Generate a temporary dir to deal with latex output files, have
my $temp_dir = tempdir(CLEANUP => 1);

die "Unable to create temp dir" if (! -d $temp_dir);

chdir $temp_dir;

my $latex_file = new FileHandle;
$latex_file->open("> latex.tex") or die "Unable to open $temp_dir/late
+x.tex";

print {$latex_file} $default->{latex_shell};

$latex_file->close;


`latex -interaction=batchmode  latex.tex> /dev/null`;
`dvips -o $temp_dir/latex.ps -E $temp_dir/latex.dvi 2> /dev/null`;
`convert -density $default->{resolution} $temp_dir/latex.ps $temp_dir/
+latex.$default->{format}`;

my $converted_file = new FileHandle;
$converted_file->open("< $temp_dir/latex.$default->{format}") or die "
+Unable to open $temp_dir/latex.$default->{format}";

print $q->header(-type=>"image/$default->{format}");
print <$converted_file>;
$converted_file->close;