polemon.org
 

l2p.cgi

This CGI script renders LaTeX math mode code as PNGs

A Demo is available here.

Grab the code here, or take a look at the source:

l2p.cgi

 1: #!/usr/bin/perl -w
 2: #
 3: #   $Id: l2p.cgi,v 1.10 2010/01/12 04:00:43 bereziak Exp $
 4: #
 5: # LaTeX math mode renderer
 6: #
 7: # Renders LaTeX math code as PNGs
 8: #
 9: # License: BSD
10: #
11:
12: use CGI;
13: use Cwd;
14:
15: my $cgi = new CGI;
16:
17: my $wdir    = '../latex';
18: my $width   = 450;
19: my $height  = 400;
20: my $density = 120;
21:
22: my $postid = $cgi->param('postid');
23:
24: print $cgi->header(-type => 'text/plain; charset=UTF-8');
25:
26: sub write_tex {
27:     my $pwidth = sprintf("%.2f", ($width / $density)) . "in";
28:     my $pheight = sprintf("%.2f", ($height / $density)) . "in";
29:
30:     if(open(LATEX, ">", $_[0])) {
31:         print LATEX <<"header_end";
32: \\nonstopmode
33: \\documentclass{minimal}
34: \\renewcommand{\\text}{\\,}
35: \\renewcommand{\\input}{\\,}
36: \\usepackage[margin=0mm, paperwidth=$pwidth, paperheight=$pheight]{geometry}
37: \\usepackage{nopageno}
38: \\usepackage[utf8]{inputenc}
39: \\usepackage{amsmath,amssymb,amsthm,latexsym}
40: \\thispagestyle{empty}
41:
42: \\begin{document}
43: \\begin{eqnarray*}
44: header_end
45:
46:         my $code = $cgi->param('code');
47:         $code =~ s/\\end\{eqnarray\\?\*?\}//g;
48:         $code =~ s/\\end\{document\}//g;
49:
50:         print LATEX $code;
51:         print LATEX "\n\\end{eqnarray*}\n\\end{document}\n";
52:         close(LATEX);
53:     }
54:     else {
55:         return 0;
56:     }
57:
58:     return 1;
59: }
60:
61: sub run_prog {
62:     unless(open(my $stdout, "-|", $_[0])) {
63:         return 0;
64:     }
65:     while(<$stdout>) { }
66:
67:     return 1;
68: }
69:
70: (($cgi->param('postid') !~ /^\d+$/) or (not $cgi->param('code')) or ($cgi->param('code') ~~ /^\s*$/)) and die "invalid postid or code!";
71:
72: chdir $wdir;
73:
74: my @files = <$postid*.png>;
75: my $fileid = $postid . "_" . scalar(@files);
76:
77: die "cannot write tex file"   unless &write_tex("$fileid.tex");
78: die "cannot create dvi file!" unless &run_prog("nice latex --interaction=nonstopmode $fileid.tex");
79: die "cannot create ps file!"  unless &run_prog("nice dvips -l =1 $fileid.dvi -o $fileid.ps");
80: die "cannot create png file!" unless &run_prog("nice convert -density $density -transparent '#ffffff' -crop " . $width . "x" . $height . "+0+0 -trim $fileid.ps $fileid.png");
81:
82: unlink("$fileid.aux");
83: unlink("$fileid.dvi");
84: unlink("$fileid.log");
85: unlink("$fileid.ps");
86: unlink("$fileid.tex");
87:
88: print "File: ", "$wdir/$fileid.png\n";
89: print "Code: '", $cgi->param('code'), "'\n";
 
l2p.cgi.txt · Last modified: 2010/08/06 22:00 by polemon
 
RSS • 2012 © --polemon Powered by: