可以通过开源的Python PDF库ReportLab
来实现PDF文件的动态生成。
ReportLab库在PyPI上提供,可以使用pip来安装:
$ pip install reportlab
在Python交互解释器中导入它来测试安装:
>>> import reportlab
如果没有抛出任何错误,证明已安装成功。
利用 Django 动态生成 PDF 的关键是 ReportLab API 作用于类文件对象,而 Django 的 FileResponse
对象接收类文件对象。
这有个 "Hello World" 示例:
import io from django.http import FileResponse from reportlab.pdfgen import canvas 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. buffer.seek(0) return FileResponse(buffer, as_attachment=True, filename='hello.pdf')
相关说明:
application/pdf
。 as_attachment=True
传递给 FileResponse
时,表示这是一个可下载附件,它会设置合适的 Content-Disposition
头,告诉 Web 浏览器弹出一个对话框,提示或确认如何处理该文档,即便设备已配置默认行为。若省略了 as_attachment
参数,浏览器会用已配置的用于处理 PDF 的程序或插件来处理该 PDF。filename
。浏览器的“另存为…”
对话框会用到它。p
)——而不是在 buffer
上调用。最后,牢记在 PDF 文件上调用 showPage()
和 save()
。
注意:ReportLab并不是线程安全的。
默认不支持中文。需要注册中文字体。
刘老师,您好!我都是把生成好的pdf放在服务器的文件夹里面,io库作为pdf临时保存地点是否可以提高生成pdf和下载pdf的速度?如果不可以,那这个库的作用是什么?盼回复,感谢~~~~
网上搜索一下,查查资料吧,看看有没有人讨论过这个问题。