Skip to content

Instantly share code, notes, and snippets.

@haoess
Created July 4, 2011 08:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save haoess/1063085 to your computer and use it in GitHub Desktop.
Save haoess/1063085 to your computer and use it in GitHub Desktop.
Create beautiful PNG images from TeX formulae via Perl CGI
#!/usr/bin/perl
use warnings;
use strict;
use Cwd;
use CGI;
use File::Path qw( rmtree );
use File::Slurp qw( read_file );
use File::Temp qw( tempdir tempfile );
my $q = CGI->new;
my $tex = $q->param('f');
my $tempdir = tempdir;
my ( undef, $tempname ) = tempfile( DIR => $tempdir );
my $cwd = getcwd;
chdir $tempdir;
open( my $latexfh, '>', "$tempname.latex" ) or die $!;
my $latex = <<"EOT";
\\documentclass[10pt]{article}
\\usepackage{amssymb,amsmath}
\\pagestyle{empty}
\\begin{document}
\\begin{displaymath}
$tex
\\end{displaymath}
\\end{document}
EOT
print $latexfh $latex;
close $latexfh;
system "/usr/bin/latex -interaction=nonstopmode $tempname.latex >/dev/null 2>&1";
system "/usr/bin/dvips -E $tempname -o >/dev/null 2>&1";
system "/usr/bin/convert -density 100 $tempname.ps $tempname.png >/dev/null 2>&1";
chdir $cwd;
my $png = read_file "$tempname.png";
rmtree $tempdir;
print $q->header( 'image/png' );
print $png;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment