5

我正在尝试生成一些 LaTeX 代码,从那里应该生成 PDF 文档。目前,我正在使用 Django 模板系统来动态创建代码,但我不知道如何从这里继续。我知道我可以将代码保存在 .tex 文件中,并使用 subprocess 运行 pdflatex 以生成 PDF。但是我在“普通”Python 中转义 LaTeX 代码时遇到了很多麻烦,所以我决定使用 Django 模板系统。有没有一种方法可以将 Django 生成的输出通过管道传输到 pdflatex?生成的代码工作正常,只是我不知道如何处理它。

提前致谢

4

1 回答 1

6

我在之前从事的一个项目中解决了同样的问题,我没有通过管道输出,而是在一个临时文件夹中创建了临时文件,因为我担心处理 LaTeX 生成的中间文件。这是我使用的代码(请注意,它已经有几年了,从我还是 Python/Django 的新手开始;我敢肯定,如果我今天写这个,我可以想出更好的东西,但这绝对对我有用):

import os
from subprocess import call
from tempfile import mkdtemp, mkstemp
from django.template.loader import render_to_string
# In a temporary folder, make a temporary file
tmp_folder = mkdtemp()
os.chdir(tmp_folder)        
texfile, texfilename = mkstemp(dir=tmp_folder)
# Pass the TeX template through Django templating engine and into the temp file
os.write(texfile, render_to_string('tex/base.tex', {'var': 'whatever'}))
os.close(texfile)
# Compile the TeX file with PDFLaTeX
call(['pdflatex', texfilename])
# Move resulting PDF to a more permanent location
os.rename(texfilename + '.pdf', dest_folder)
# Remove intermediate files
os.remove(texfilename)
os.remove(texfilename + '.aux')
os.remove(texfilename + '.log')
os.rmdir(tmp_folder)
return os.path.join(dest_folder, texfilename + '.pdf')

dest_folder变量通常设置在媒体目录中的某个位置,以便可以静态提供 PDF。返回的值是磁盘上文件的路径。其 URL 的逻辑由设置dest_folder.

于 2010-07-16T00:28:08.253 回答