1. 程式人生 > >python reportlab 生成pdf (一)

python reportlab 生成pdf (一)

關於python reportlab 庫的學習 一

安裝ReprotLab

可以使用如下指令將ReprotLab庫匯入Python互動直譯器以測試安裝情況:

>>> import reportlab

Demo

如果此命令沒有輸出任何錯誤則表明安裝成功。

下面是一個hello world例子

這裡例子用的是django,如果直接python執行的話,去掉return ,然後canvas引數為pdf檔名就可以

from reportlab.pdfgen import canvas
from django.http import HttpResponse
 
def some_view(request):
    # Create the HttpResponse object with the appropriate PDF headers.
    #mimetype 已經過時,使用content-type代替
    # response=HttpResponse(mimetype='application/pdf')
    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


總結

這樣就可以簡單的實現使用python製作pdf,但是這種方法,需要手動佈局,並且操作繁瑣。真正用來製作報表的話,應該使用:

from reportlab.platypus import SimpleDocTemplate