【问题标题】:zipping up xhtml2pdf pdf's with zipfile用 zipfile 压缩 xhtml2pdf pdf
【发布时间】:2012-02-05 09:07:56
【问题描述】:

我正在使用以下函数从 xhthml2pdf 生成我的 pdf 文件

def render_to_pdf(template_src, context_dict, filename):
    template = get_template(template_src)
    context = Context(context_dict)
    html  = template.render(context)
    result = StringIO.StringIO()

    pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), encoding='UTF-8',  
            dest=result, 
            link_callback=fetch_resources )
    return pdf

接下来,我正在使用以下函数来尝试压缩 pdf 对象列表

def generate_zip(object_list, template):
    result = StringIO.StringIO()
    zipped = zipfile.ZipFile(result, "w")
    for object in object_list:
        zipped.writestr("test.pdf", object)
    zipped.close()
    return result.getvalue()

但我收到以下错误

TypeError: object of type 'pisaContext' has no len()

这让我相信我没有生成正确的压缩对象。所以我的问题是,如何使用 xhtml2pdf 生成适合 zipfile 的 pd 文件?

【问题讨论】:

  • 您的代码清单不完整或损坏。 generate_zip 中的 pdf 变量可能是一个全局变量 (?),除了 render_to_pdf 之外没有分配给任何地方,但它返回它,所以它可能不应该设置全局变量。
  • 啊,你是对的。现已更新。

标签: python pdf-generation zipfile xhtml2pdf


【解决方案1】:

pdf 必须是字符串(字节)。也许,您需要使用 render_to_pdf 的结果中的 result.getvalue()?

我没有广泛使用 pisa:PisaDocument 也有一个序列化方法:pdf.dest.getvalue()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多