我可以在内存文件上 运行 pdflatex 吗?

Can I run pdflatex on an in-memory file?

我要生成一系列 pdf 文件,其内容将在 Python (2.7) 中生成。一个常规的解决方案是将 .tex 内容保存在某个目录中,在文件上调用 pdflatex,之后读取 pdf 文件,以便最终将文件放在相关的地方。如下所示:

import os

texFile = \
"""\documentclass[11pt,a4paper,final]{article}
\begin{document}
Hello, world!
\end{document}
""" # Clearly will a more awesome file be generated here!

with open('hello.tex', 'w') as f:
    f.write(texFile)
os.system('pdflatex hello.tex')
pdfFile = open('hello.pdf', 'rb').read()
# Now place the file somewhere relevant ...

我想要相同的过程,但在内存中进行,以提高速度并避免文件泄漏到某些文件夹中。所以我的问题是,如何在内存中 运行 pdflatex 并将生成的 pdf 提取回 Python?

看看tex。它为 TeX 命令行工具提供内存中 API。例如:

>>> from tex import latex2pdf
>>> document = ur"""
... \documentclass{article}
... \begin{document}
... Hello, World!
... \end{document}
... """
>>> pdf = latex2pdf(document)

>>> type(pdf)
<type 'str'>
>>> print "PDF size: %.1f KB" % (len(pdf) / 1024.0)
PDF size: 5.6 KB
>>> pdf[:5]
'%PDF-'
>>> pdf[-6:]
'%%EOF\n'

只需运行pip install tex即可安装。另请注意,对于字符串块,您可以简单地在前面添加 r 以使其成为原始字符串。这样你就不必转义所有的反斜杠。