reportlab是基于python的开源免费的pdf生成工具,据说有很多应用使用reportlab生成pdf,根据最近几天的琢磨,虽然最后搞定了模板,不得不说,这种工具是十分残忍的。据说他们收费版本reportlab plus可以使用RML(十分接近HTML),这些就不扯了。
reportlab绘制pdf的基本流程是,先构建一个Canvas对象,这个对象作用于一个文件,或者二进制IO,初始化以后,进行一系列绘制动作(画线,写字,插入图片等等。。),绘制结束以后,保存绘制结果到文件或者二进制IO。django可以利用response作为reportlab的Canvas的受体,并发送给客户端。
直接上代码
from reportlab.pdfgen import canvas
from django.http import HttpResponse
def some_view(request):
#创建HttpResponse对象,并制定response的头部为pdf格式
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"'
#创建PDF对象,初始化时,使用response作为文件.
p = canvas.Canvas(response)
’‘’
标准的cavas初始化是这样的
p = canvas.Canvas("filename")
默认尺寸是A4,可以接收IO对象或者是文件名
‘’‘
#在pdf中绘制内容
#这里只是简单打印"hello wordls"
p.drawString(100, 100, "Hello world.")
# p.showPage()清初样式设定、p.save()将生成的pdf保存到文件
p.showPage()
p.save()
#返回给客户端
return response
说明:
content_type='application/pdf' 指定文件类型是pdf,避免浏览器尝试使用HTML打开文件。
content-disposition :attachment告诉浏览器,下载pdf文件,而不是直接打开,如果移除这一部分,这样的话,浏览器会尝试使用插件或者其他可能的方式直接打开pdf。
文件名可以按照自己的需求定制.
response['Content-Disposition'] = 'filename="somefilename.pdf"'
记住:Django始终没有参与pdf的制作,它只是pdf的搬运工。pdf是canvas.Canvas制作的
canvas.Canvas(),接收一个类文件对象作为参数,比如文件名,二进制IO,或者是HttpResponse。
最后,通过 showPage()j结束当前页绘制,save()保存pdf到文件/二进制IO。
如果想制作复杂pdf,可以使用ByteIO作为文件对象存储pdf文件,然后写到response里。
from io import BytesIO
from reportlab.pdfgen import canvas
from django.http import HttpResponse
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"'
buffer = BytesIO()
# Create the PDF object, using the BytesIO object 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.
p.showPage()
p.save()
# Get the value of the BytesIO buffer and write it to the response.
pdf = buffer.getvalue()
buffer.close()
response.write(pdf)
return response
原文:https://docs.djangoproject.com/en/1.10/howto/outputting-pdf/
参考信息:reportlab
reportlab绘制东西十分辛苦,如果没有真实需求还是不要花太多时间。