Django:输出要继续的文本文件

时间:2018-03-09 17:05:48

标签: python django latex tex

我有一个小的django应用程序,用于管理我的患者数据(我是python / django中级医生) 我使用LaTeX通过输出我的报告这样的视图函数

def consultation_pdf(request, pk2, pk1):
    entry = Consultation.objects.get(pk=pk2)
    source = Patient.objects.get(pk=pk1)
#    context = Context({ 'consultation': entry, 'patient': source })
    context = dict({'consultation': entry, 'patient': source})
    template = get_template('clinic/consultation.tex')
    rendered_tpl = template.render(context, request).encode('utf-8')
# Python3 only. For python2 check out the docs!
    with tempfile.TemporaryDirectory() as tempdir:
        # Create subprocess, supress output with PIPE and
        # run latex twice to generate the TOC properly.
        # Finally read the generated pdf.
        for i in range(2):
            process = Popen(
                                           ['xelatex', '-output-directory', tempdir],
                                           stdin=PIPE,
                                           stdout=PIPE,
                                          )
        process.communicate(rendered_tpl)
        with open(os.path.join(tempdir, 'texput.pdf'), 'rb') as f:
            pdf = f.read()
r = HttpResponse(content_type='application/pdf')
r.write(pdf)
return r

现在我需要切换到ConTeXT,因为它可以满足我的需求。

到目前为止,最大的问题是ConTeXT需要将source文件 pdf同时保存在磁盘上,而不是简单地管道stdinstdout分别。

我怎么能设法完成这项任务?到目前为止,我发现的唯一解决方法是生成tex文件,然后手动运行。

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

为什么这是一个问题?在调用上下文之前,可以将输入文件保存到磁盘。我不确定上下文的命令行是如何工作的,但这是保存文件的方式:

import uuid
import os

def consultation_pdf(request, pk2, pk1):
    entry = Consultation.objects.get(pk=pk2)
    source = Patient.objects.get(pk=pk1)
    #    context = Context({ 'consultation': entry, 'patient': source })
    context = dict({'consultation': entry, 'patient': source})
    template = get_template('clinic/consultation.tex')
    rendered_tpl = template.render(context, request)
    # save the file to disk
    filename = uuid.uuid4()
    # Python3 only. For python2 check out the docs!
    with tempfile.TemporaryDirectory() as tempdir:
        filename = os.path.join(tempdir, filename.hex)
        with open(filename, 'w', encoding='utf8') as infile:
            infile.write(rendered_tpl)
        # Create subprocess, supress output with PIPE and
        # run latex twice to generate the TOC properly.
        # Finally read the generated pdf.
        for i in range(2):
            process = Popen(
                ['context', filename, '-output-directory', 
                  tempdir],
                stdin=PIPE,
                stdout=PIPE,)
        process.communicate(rendered_tpl)
        with open(os.path.join(tempdir, 'texput.pdf'), 'rb') as f:
            pdf = f.read()
            r = HttpResponse(content_type='application/pdf')
            r.write(pdf)
            return r