這對我來說是有效的,由Krzysiek的建議使用StringIO
。這裏canvas
是由matplotlib創建的canvas
對象。
#Create the file-like objects from canvases
file_like_1 = StringIO.StringIO()
file_like_2 = StringIO.StringIO()
#... etc...
canvas_1.print_pdf(file_like_1)
canvas_2.print_pdf(file_like_2)
#...etc....
#NOW create the zipfile
response = HttpResponse(mimetype='application/zip')
response['Content-Disposition'] = 'filename=all_plots.zip'
buff = StringIO.StringIO()
archive = zipfile.ZipFile(buff,'w',zipfile.ZIP_DEFLATED)
archive.writestr('plot_1.pdf',file_like_1.getvalue())
archive.writestr('plot_2.pdf',file_like_2.getvalue())
#..etc...
archive.close()
buff.flush()
ret_zip = buff.getvalue()
buff.close()
response.write(ret_zip)
return response
這一切的荏苒部分從https://code.djangoproject.com/wiki/CookBookDynamicZip
拍攝您可以使用Python的GZip庫在內存中壓縮。但我不確定您是否可以在內存中製作PDF。你也可以查看(http://stackoverflow.com/questions/6413441/python-pdf-library)和xhtml2pdf。 – pranshus