代码之家  ›  专栏  ›  技术社区  ›  Uku Loskit

如何使用LaTeX以编程方式生成PDF?

  •  5
  • Uku Loskit  · 技术社区  · 14 年前

    我正在尝试生成一些LaTeX代码,从中可以生成PDF文档。

    提前谢谢

    1 回复  |  直到 14 年前
        1
  •  6
  •   Aram Dulyan    14 年前

    我在以前工作过的一个项目中处理同样的问题,我没有将输出管道化,而是在一个临时文件夹中创建临时文件,因为我担心处理中间文件。这是我使用的代码(请注意,这是几年前的代码,从我还是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 目标文件夹