<分区>
我正在寻找一个 C 或 C++ 库(或更聪明的解决方案),它可以从 LaTeX 代码生成图像文件 (PNG|jpeg)。使用包是先决条件。
现在我正在考虑将一个 .tex 文件编译成一个 .dvi 并使用 dvipng 来获得一个 .PNG。
还有可能将 .tex 文件编译为 .ps 文件,然后通过 pstopng 或 pstoedit 等外部实用程序将其转换为 .PNG .
但这些解决方案很麻烦,而且并不总是可移植的。我想透明地将此转换集成到我的程序中。
<分区>
我正在寻找一个 C 或 C++ 库(或更聪明的解决方案),它可以从 LaTeX 代码生成图像文件 (PNG|jpeg)。使用包是先决条件。
现在我正在考虑将一个 .tex 文件编译成一个 .dvi 并使用 dvipng 来获得一个 .PNG。
还有可能将 .tex 文件编译为 .ps 文件,然后通过 pstopng 或 pstoedit 等外部实用程序将其转换为 .PNG .
但这些解决方案很麻烦,而且并不总是可移植的。我想透明地将此转换集成到我的程序中。
最佳答案
我之前已经多次使用 dvipng 路由,但是是在 python 中。这是一条普通的路,很多人都走过。这是代码,可以让您入门,以防万一有人需要 Python 代码。 我知道你问的是 C/C++;这是为入门者或其他人准备的。 这是为了生成方程式,但将其适用于更一般的结构将是微不足道的。它确实支持包。
在透明集成方面,我感受到了你的痛苦。当然不是每个人都有 tex/latex,如果没有,通常会很痛苦。我认为,最好的方法是将该功能作为 Web 服务提供 - 但当然这并不总是一种选择。
最后,注意 dvipng 的所有选项。它们通过各种抗锯齿选项等控制外观。我对它们进行了大量调整以获得我认为好看的效果。
def geneq(f, eq, dpi, wl, outname, packages):
# First check if there is an existing file.
eqname = os.path.join(f.eqdir, outname + '.png')
# Open tex file.
tempdir = tempfile.gettempdir()
fd, texfile = tempfile.mkstemp('.tex', '', tempdir, True)
basefile = texfile[:-4]
g = os.fdopen(fd, 'w')
preamble = '\documentclass{article}\n'
for p in packages:
preamble += '\usepackage{%s}\n' % p
preamble += '\pagestyle{empty}\n\\begin{document}\n'
g.write(preamble)
# Write the equation itself.
if wl:
g.write('\\[%s\\]' % eq)
else:
g.write('$%s$' % eq)
# Finish off the tex file.
g.write('\n\\newpage\n\end{document}')
g.close()
exts = ['.tex', '.aux', '.dvi', '.log']
try:
# Generate the DVI file
latexcmd = 'latex -file-line-error-style -interaction=nonstopmode ' + \
'-output-directory %s %s' % (tempdir, texfile)
p = Popen(latexcmd, shell=True, stdout=PIPE)
rc = p.wait()
if rc != 0:
for l in p.stdout.readlines():
print ' ' + l.rstrip()
exts.remove('.tex')
raise Exception('latex error')
dvifile = basefile + '.dvi'
dvicmd = 'dvipng --freetype0 -Q 9 -z 3 --depth -q -T tight -D %i -bg Transparent -o %s %s' % (dpi, eqname, dvifile)
# discard warnings, as well.
p = Popen(dvicmd, shell=True, stdout=PIPE, stderr=PIPE)
rc = p.wait()
if rc != 0:
print p.stderr.readlines()
raise Exception('dvipng error')
depth = int(p.stdout.readlines()[-1].split('=')[-1])
finally:
# Clean up.
for ext in exts:
g = basefile + ext
if os.path.exists(g):
os.remove(g)
关于c++ - 在 C 或 C++ 中从 LaTeX 制作 PNG|jpeg,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1913055/