代码之家  ›  专栏  ›  技术社区  ›  PhoebeB

使用PISA将PDF写入磁盘

  •  7
  • PhoebeB  · 技术社区  · 16 年前

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

    1 回复  |  直到 13 年前
        1
  •  12
  •   beeftaco    13 年前

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