【问题标题】:Can I run pdflatex on an in-memory file?我可以在内存文件上运行 pdflatex 吗?
【发布时间】:2016-09-12 14:55:24
【问题描述】:

我将生成一系列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?

【问题讨论】:

    标签: python pdflatex


    【解决方案1】:

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

    【讨论】:

    • 感谢您的回复。我已经尝试过了,但收到以下错误消息: ValueError: close_fds is not supported on Windows platforms if you redirect stdin/stdout/stderr.我正在使用 Windows 7。我还没有找到解决方案,也无法成功安装它的继任者“texcaller”,我认为这是因为它没有为 Windows 打包。但我还不确定。
    • 这听起来更像是 Windows 兼容性问题。我使用的是 Linux,所以我无法重现该问题。快速搜索显示其他项目如何修复它:geventpy4jipython。还要确保您使用的是来自 PyPI 的最新包版本。 ValueError 表示重定向出错,因此在 UNIX 系统下使用管道。你用 Cygwin 吗?
    • 请注意texcaller 仍然在后台调用pdflatex,将文件写入磁盘,因此从技术上讲它不是“内存中”。在临时目录中通过subprocess.run 运行pdflatex 具有相同(甚至更好)的执行时间,并且避免了所有的编译模糊。
    猜你喜欢
    • 2011-06-03
    • 1970-01-01
    • 2014-05-04
    • 1970-01-01
    • 1970-01-01
    • 2015-09-29
    • 2011-10-31
    • 1970-01-01
    相关资源
    最近更新 更多