Skip to main content
 首页 » 编程设计

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

2025年04月02日852php

我要生成一系列 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 即可安装它。另请注意,对于字符串 block ,您可以简单地在前面添加 r 以使其成为原始字符串。这样您就不必转义所有反斜杠。