我已经阅读了一些关于这个问题的帖子,但是大多数帖子对我的情况没有帮助,我正在尝试将编码的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'进行编码:字符映射到
我真的不明白我做错了什么以及如何解决它,有什么建议吗?
答案 0 :(得分:0)
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)