我在之前从事的一个项目中解决了同样的问题,我没有通过管道输出,而是在一个临时文件夹中创建了临时文件,因为我担心处理 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
.