我正在尝试从django视图生成并输出PDF。我按照django documentation using ReportLab中的示例进行了操作,但下载的PDF文件未在任何PDF阅读器中打开。
我使用Python 3.7.0,Django == 2.1.3,reportlab == 3.5.12。我尝试将content_type="application/pdf"
添加到'FileResponse`但仍然有同样的问题。
import io
from django.http import FileResponse
from reportlab.pdfgen import canvas
def printPDF(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)
p.drawString(100, 100, "Hello world.")
p.showPage()
p.save()
return FileResponse(buffer, as_attachment=True, filename='hello.pdf')
生成的PDF应该在所有PDF阅读器中打开。但我得到'无法加载PDF文档'。
BytesIO
和FileResponse
的相互作用似乎有些可疑。以下对我有用。
def printPDF(request):
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename=hello.pdf'
p = canvas.Canvas(response)
p.drawString(100, 100, "Hello world.")
p.showPage()
p.save()
return response
使用buffer = BytesIO()
代替文件来存储pdf文档。在使用FileResponse返回之前,您需要将流位置重置为其开头:
buffer.seek(io.SEEK_SET)
现在pdf下载应该按预期工作。