4 Converts LaTeX math to png images.
5 Run latexmath2png.py --help for usage instructions.
10 Kamil Kisiel <kamil@kamilkisiel.net>
11 URL: http://www.kamilkisiel.net
14 2007/04/20 - Initial version
17 - Make handling of bad input more graceful?
20 Some ideas borrowed from Kjell Fauske's article at http://fauskes.net/nb/htmleqII/
22 Licensed under the MIT License:
24 Copyright (c) 2007 Kamil Kisiel <kamil@kamilkisiel.net>
26 Permission is hereby granted, free of charge, to any person obtaining a copy
27 of this software and associated documentation files (the "Software"), to deal
28 in the Software without restriction, including without limitation the rights
29 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
30 copies of the Software, and to permit persons to whom the Software is
31 furnished to do so, subject to the following conditions:
33 The above copyright notice and this permission notice shall be included in
34 all copies or substantial portions of the Software.
36 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
37 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
38 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
39 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
40 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
41 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
49 from StringIO
import StringIO
50 from subprocess
import *
60 preamble =
'\documentclass{article}\n'
62 preamble +=
"\usepackage{%s}\n" % p
64 preamble +=
"\pagestyle{empty}\n\\begin{document}\n"
70 latexcmd =
'latex -file-line-error-style -interaction=nonstopmode -output-directory %s %s'\
72 p = Popen(latexcmd, shell=
True, stdout=PIPE)
78 raise Exception(
'latex error')
82 dvifile = infile.replace(
'.tex',
'.dvi')
83 outprefix = os.path.join(outdir, prefix)
84 dvicmd =
"dvipng --freetype0 -Q 8 --depth -q -T tight -D %i -z 3 -bg Transparent "\
85 "-o %s.png %s" % (dpi, outprefix, dvifile)
86 p = Popen(dvicmd, shell=
True, stdout=PIPE)
89 raise Exception(
'dvipng error')
90 depth = int(p.stdout.readlines()[-1].split(
'=')[-1])
93 basefile = infile.replace(
'.tex',
'')
94 tempext = [
'.aux',
'.dvi',
'.log' ]
102 def math2png(eq, outdir, packages = default_packages, prefix = '', dpi = 100):
106 workdir = tempfile.gettempdir()
109 fd, texfile = tempfile.mkstemp(
'.tex',
'', workdir,
True)
113 f = os.fdopen(fd,
'w')
115 f.write(
"$%s$\n" % eq)
116 f.write(
'\end{document}')
128 def math2pngwl(eq, outdir, packages = default_packages, prefix = '', dpi = 100):
132 workdir = tempfile.gettempdir()
135 fd, texfile = tempfile.mkstemp(
'.tex',
'', workdir,
True)
139 f = os.fdopen(fd,
'w')
141 f.write(
"\\[%s\\]\n\\newpage\n" % eq)
142 f.write(
'\end{document}')