【发布时间】:2019-05-31 15:48:55
【问题描述】:
我正在尝试从 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 文档”。
【问题讨论】:
标签: django pdf-generation reportlab