django 動態生成PDF文件

能夠經過開源的Python PDF庫ReportLab來實現PDF文件的動態生成。django

1、安裝ReportLab

ReportLab庫在PyPI上提供,能夠使用pip來安裝:canvas

$ pip install reportlab

在Python交互解釋器中導入它來測試安裝:瀏覽器

>>> import reportlab 

若是沒有拋出任何錯誤,證實已安裝成功。安全

2、編寫視圖

ReportLab的API能夠處理於相似於文件(file-like)的對象。下面是一個 「Hello World」的例子:app

from reportlab.pdfgen import canvas from django.http import HttpResponse def some_view(request): # 建立帶有PDF頭部定義的HttpResponse對象 response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"' # 建立一個PDF對象,並使用響應對象做爲它要處理的‘文件’ p = canvas.Canvas(response) # 經過PDF對象的drawString方法,寫入一條信息。具體參考模塊的官方文檔說明。 p.drawString(100, 100, "Hello world.") # 關閉PDF對象 p.showPage() p.save() return response 

相關說明:函數

  • 響應對象的MIME類型爲application/pdf。 這會告訴瀏覽器,文檔是個PDF文件而不是HTML文件。
  • 響應對象設置了附加的Content-Disposition協議頭,含有PDF文件的名稱。
  • 文件名能夠是任意的,瀏覽器會在「另存爲...」對話框等中使用。
  • Content-Disposition以'attachment'開頭,強制讓瀏覽器彈出對話框來提示或者確認。
  • Canvas函數接受一個相似於文件的對象,而HttpResponse對象正好合適。
  • 最後,在PDF文件上調用showPage()和save()方法很是重要。
  • 注意:ReportLab並非線程安全的。

3、複雜的PDF

使用ReportLab建立複雜的PDF文檔時,能夠考慮使用io庫做爲PDF文件的臨時保存地點。這個庫提供了一個相似於文件的對象接口,很是實用。 下面的例子是上面的「Hello World」示例採用io重寫後的樣子:測試

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
相關文章
相關標籤/搜索