9

我可以在浏览器中的 django 中生成 .pdf 的 pisa 文件,但是如果我想自动将文件写入磁盘怎么办?我要做的是能够在指定的时间点生成一个.pdf版本的文件并保存在一个uploads目录中,这样就没有浏览器交互了。这可能吗?

4

1 回答 1

15

对的,这是可能的。例如,使用Greg Newman的代码作为入门:

from django.template.loader import get_template
from django.template import Context
import ho.pisa as pisa
import cStringIO as StringIO
import cgi

def write_pdf(template_src, context_dict, filename):
    template = get_template(template_src)
    context = Context(context_dict)
    html  = template.render(context)
    result = open(filename, 'wb') # Changed from file to filename
    pdf = pisa.pisaDocument(StringIO.StringIO(
        html.encode("UTF-8")), result)
    result.close()

您只需要使用模板、字典中的数据和文件名调用 write_pdf。

于 2010-05-24T20:23:25.017 回答