这是我第一次使用reportlab。我从Django文档中复制了确切的代码。 https://docs.djangoproject.com/en/2.1/howto/outputting-pdf/。当我保存文件时,将其另存为纯文本文档(文本/纯文本),名称保持不变hello.pdf,没有文本。
p = canvas.Canvas(buffer) 在这一行中,如果我写文件名“ hello.pdf”而不是缓冲区,并从它起作用的fileresponse方法中删除缓冲区,它会自动保存为pdf文件,但是我无法提示用户保存文件,并且有两个pdf中的页面。
def some_view(request):
# Create a file-like buffer to receive PDF data.
buffer = io.BytesIO()
# Create the PDF object, using the buffer as its "file."
p = canvas.Canvas(buffer)
# Draw things on the PDF. Here's where the PDF generation happens.
# See the ReportLab documentation for the full list of functionality.
p.drawString(100, 100, "Hello world.")
# Close the PDF object cleanly, and we're done.
p.showPage()
p.save()
# FileResponse sets the Content-Disposition header so that browsers
# present the option to save the file.
return FileResponse(buffer, as_attachment=True, filename='hello.pdf')
我尝试在Django文档提供的代码中指定content_type ='application / pdf',但仍然将其保存为纯文本文档。我猜想File响应不能像Django文档中提到的那样从filename参数中猜测文件的类型。
类FileResponse(open_file,as_attachment = False,filename ='',** kwargs) 如果open_file没有名称,或者open_file的名称不合适,请使用filename参数提供自定义文件名。
添加了as_attachment和filename关键字参数。另外,如果FileResponse可以猜出ContentHeader,则设置它。
如果我使用2.0 django文档中的代码,它将起作用。最新的django文档2.1中是否有bug?我根据此官方链接https://bitbucket.org/rptlab/reportlab/src/927995d54048767531a4ad4a0648e46064b0c4c7/README.txt?at=default&fileviewer=file-view-default环境安装了所有依赖项-ubuntu 18.04lts,pycharm,Python 3.5.6,reportlab 3.5.12。
答案 0 :(得分:0)
您需要将缓冲区位置重置为开始才能返回FileResponse:
buffer.seek(io.SEEK_SET)
否则,将从缓冲区的结尾(在写入画布之后)开始读取缓冲区,并返回一个空文件。
从v2.1开始,此内容在文档中已丢失,应予以修复。