我使用Django 2.1.4,并使用Django示例创建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')
开始下载,但从未结束。怎么了? 旧版本可以正常工作
def some_view(request):
# Create the HttpResponse object with the appropriate PDF headers.
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"'
# Create the PDF object, using the response object as its "file."
p = canvas.Canvas(response)
# 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()
return response
答案 0 :(得分:3)
我将看一下这个示例(查询集除外),看看是否可行,类似How can i display my data in database and export it to pdf -Django
获取BytesIO缓冲区的值并将其写入响应。
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="WishList.pdf"'
from reportlab.pdfgen import canvas
buffer = BytesIO()
p = canvas.Canvas(buffer)
p.drawString(100, 100, "Hello world.")
p.showPage()
p.save()
pdf = buffer.getvalue()
buffer.close()
response.write(pdf)
return response
答案 1 :(得分:0)
信不信由你,我建议您使用旧版本。要使其与FileResponse
一起使用,请尝试以下操作:
# FileResponse sets the Content-Disposition header so that browsers
# present the option to save the file.
response = FileResponse(buffer, as_attachment=True, filename='hello.pdf', content_type='application/pdf')
# set the content length to let the browser know how many bytes to expect
response['Content-Length'] = bugger.getbuffer().nbytes
return response