gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:23:55 25 4
gpt4 key购买 nike

我要生成一系列 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 以使其成为原始字符串。这样您就不必转义所有反斜杠。

关于python - 我可以在内存文件上运行 pdflatex 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39453227/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com