【问题标题】:How to save an encoded pdf in a zip file using django?如何使用 django 将编码的 pdf 保存在 zip 文件中?
【发布时间】:2017-11-21 17:57:40
【问题描述】:

我已经阅读了一些关于这个问题的帖子,但其中大多数对我的情况没有帮助,我正在尝试将编码的 pdf 保存在一个 zip 文件中(我正在使用 Docraptor API 来生成 pdf,它返回编码的pdf)。

def toZip(request, ...):
    ...
    response = docraptor_api_call() #api call to generate pdf (encoded pdf)

    with open('creation.pdf', 'wb') as f:
        f.write(response)

    #decode pdf
    with open(f.name, 'rb') as pdf:
        # this will download the pdf to the user
        # doc = HttpResponse(pdf.read(), content_type='application/pdf')
        # doc['Content-Disposition'] = "attachment; filename=filename.pdf" 
        # return doc

        zip_io = io.BytesIO()
        # create zipFile
        zf = zipfile.ZipFile(zip_io, mode='w')

        # write PDF in ZIP ?
        save_zf = zf.write(pdf.read())

        # save zip to FileField
        zip = ZipStore.objects.create(zip=save_zf)

在尝试顶部的代码时,我收到此错误:

UnicodeEncodeError: 'charmap' 编解码器无法对位置 43 中的字符 '\u2019' 进行编码:字符映射到

我真的不明白我做错了什么以及我应该如何解决它,有什么建议吗?

【问题讨论】:

  • 这里只是从臀部发射,但听起来您需要更改错误来源所使用的编码。
  • @SuperStew 编码是 utf-8,我不确定错误来自那个
  • 您可能需要将其更改为其他内容。或者过滤掉不兼容的字符。

标签: python django zip


【解决方案1】:

You've got an error in the way you're calling zf.write。您应该使用:

# ZipFile.write would take the the file to write, not bytes to be written.
# f.name is the name of the file in the zip archive. So if I passed 
# in "foo.txt", "1", I'd get a file named `foo.txt` after decompressing, and its
# contents would be 1
zf.writestr(f.name, pdf.read())

此方法似乎没有返回任何内容,因此您需要将其更改为:zip = ZipStore.objects.create(zip=save_zf) 可能为:

zip = ZipStore.objects.create(zip=zip_io)

【讨论】:

  • write 方法不返回任何内容。 objects.create 需要被赋予其他东西。
猜你喜欢
  • 1970-01-01
  • 2012-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多