使用Pisa将pdf写入磁盘

时间:2010-05-24 19:49:06

标签: django pisa

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

1 个答案:

答案 0 :(得分:12)

是的,这是可能的。例如,使用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()

您只需要使用模板,dict中的数据和文件名调用write_pdf。

相关问题