我正在使用TeX宏包Context生成pdf。 Context源文件是使用Django模板生成的,内容使用Pandoc从HTML(存储在数据库中)转换为Context的语法。由于Pandoc没有本机python绑定,我创建了以下模板过滤器以将HTML转换为Context:
def html2context(value):
"""
Runs pandoc to convert from HTML to Context.
Syntax::
{{ value|html2context }}
"""
cmd = 'pandoc -f html -t context'
p1 = subprocess.Popen(cmd.split(" "), stdout=subprocess.PIPE, stdin=subprocess.PIPE)
(stdout, stderr) = p1.communicate(input=value.encode('utf-8'))
return mark_safe(stdout)
问题是,为了生成我的pdf,我已经多次调用模板过滤器,结束了非常缓慢的转换过程。我必须多次调用过滤器的原因是因为我的模板混合了数据库中的内容和原始上下文命令来构建我的文档:HTML并未涵盖上下文中我需要的所有可能性。我的模板的最小示例如下所示:
{% for plugin in intro %}
{{ plugin.text.body|html2context }}
\page[emptyodd]
{% endfor %}
您是否知道如何才能使转换过程不那么次优?
由于
答案 0 :(得分:0)
我认为更好的解决方案是直接在ConTeXT中创建模板,并生成如下视图:
from django.http import HttpResponse
from django.template import Context
from django.template.loader import get_template
from subprocess import Popen, PIPE
import tempfile
from .models import Entry
def entry_as_pdf(request, pk):
entry = Entry.objects.get(pk=pk)
context = Context({
'content': entry.content,
})
template = get_template('my_latex_template.tex')
rendered_tpl = template.render(context).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(
['context', '-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['Content-Disposition'] = 'attachment; filename=texput.pdf'
r.write(pdf)
return r
注意有一个循环可以运行context
命令两次,以防你在文档中包含TOC或参考书目参考,