国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

利用Python的Django框架生成PDF文件的教程

2019-11-25 17:08:52
字體:
供稿:網(wǎng)友

便攜文檔格式 (PDF) 是由 Adobe 開發(fā)的格式,主要用于呈現(xiàn)可打印的文檔,其中包含有 pixel-perfect 格式,嵌入字體以及2D矢量圖像。 You can think of a PDF document as the digital equivalent of a printed document; indeed, PDFs are often used in distributing documents for the purpose of printing them.

可以方便的使用 Python 和 Django 生成 PDF 文檔需要歸功于一個出色的開源庫, ReportLab (http://www.reportlab.org/rl_toolkit.html) 。動態(tài)生成 PDF 文件的好處是在不同的情況下,如不同的用戶或者不同的內(nèi)容,可以按需生成不同的 PDF 文件。 The advantage of generating PDF files dynamically is that you can create customized PDFs for different purposes say, for different users or different pieces of content.

下面的例子是使用 Django 和 ReportLab 在 KUSports.com 上生成個性化的可打印的 NCAA 賽程表 (tournament brackets) 。
安裝 ReportLab

在生成 PDF 文件之前,需要安裝 ReportLab 庫。這通常是個很簡單的過程: Its usually simple: just download and install the library from http://www.reportlab.org/downloads.html.

Note

如果使用的是一些新的 Linux 發(fā)行版,則在安裝前可以先檢查包管理軟件。 多數(shù)軟件包倉庫中都加入了 ReportLab 。

比如,如果使用(杰出的) Ubuntu 發(fā)行版,只需要簡單的 apt-get install python-reportlab 一行命令即可完成安裝。

使用手冊(原始的只有 PDF 格式)可以從 http://www.reportlab.org/rsrc/userguide.pdf 下載,其中包含有一些其它的安裝指南。

在 Python 交互環(huán)境中導(dǎo)入這個軟件包以檢查安裝是否成功。

>>> import reportlab

如果剛才那條命令沒有出現(xiàn)任何錯誤,則表明安裝成功。
編寫視圖

和 CSV 類似,由 Django 動態(tài)生成 PDF 文件很簡單,因為 ReportLab API 同樣可以使用類似文件對象。

下面是一個 Hello World 的示例:

from reportlab.pdfgen import canvasfrom django.http import HttpResponsedef hello_pdf(request):  # Create the HttpResponse object with the appropriate PDF headers.  response = HttpResponse(mimetype='application/pdf')  response['Content-Disposition'] = 'attachment; filename=hello.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

需要注意以下幾點:

    這里我們使用的 MIME 類型是 application/pdf 。這會告訴瀏覽器這個文檔是一個 PDF 文檔,而不是 HTML 文檔。 如果忽略了這個參數(shù),瀏覽器可能會把這個文件看成 HTML 文檔,這會使瀏覽器的窗口中出現(xiàn)很奇怪的文字。 If you leave off this information, browsers will probably interpret the response as HTML, which will result in scary gobbledygook in the browser window.

    使用 ReportLab 的 API 很簡單: 只需要將 response 對象作為 canvas.Canvas 的第一個參數(shù)傳入。

    所有后續(xù)的 PDF 生成方法需要由 PDF 對象調(diào)用(在本例中是 p ),而不是 response 對象。

    最后需要對 PDF 文件調(diào)用 showPage() 和 save() 方法(否則你會得到一個損壞的 PDF 文件)。

復(fù)雜的 PDF 文件

如果您在創(chuàng)建一個復(fù)雜的 PDF 文檔(或者任何較大的數(shù)據(jù)塊),請使用 cStringIO 庫存放臨時生成的 PDF 文件。 cStringIO 提供了一個用 C 編寫的類似文件對象的接口,從而可以使系統(tǒng)的效率最高。

下面是使用 cStringIO 重寫的 Hello World 例子:

from cStringIO import StringIOfrom reportlab.pdfgen import canvasfrom django.http import HttpResponsedef hello_pdf(request):  # Create the HttpResponse object with the appropriate PDF headers.  response = HttpResponse(mimetype='application/pdf')  response['Content-Disposition'] = 'attachment; filename=hello.pdf'  temp = StringIO()  # Create the PDF object, using the StringIO object as its "file."  p = canvas.Canvas(temp)  # 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 StringIO buffer and write it to the response.  response.write(temp.getvalue())  return response

其它的可能性

使用 Python 可以生成許多其它類型的內(nèi)容,下面介紹的是一些其它的想法和一些可以用以實現(xiàn)它們的庫。 Here are a few more ideas and some pointers to libraries you could use to implement them:

    ZIP 文件 :Python 標準庫中包含有 zipfile 模塊,它可以讀和寫壓縮的 ZIP 文件。 它可以用于按需生成一些文件的壓縮包,或者在需要時壓縮大的文檔。 如果是 TAR 文件則可以使用標準庫 tarfile 模塊。

    動態(tài)圖片 : Python 圖片處理庫 (PIL; http://www.pythonware.com/products/pil/) 是極好的生成圖片(PNG, JPEG, GIF 以及其它許多格式)的工具。 它可以用于自動為圖片生成縮略圖,將多張圖片壓縮到單獨的框架中,或者是做基于 Web 的圖片處理。

    圖表 : Python 有許多出色并且強大的圖表庫用以繪制圖表,按需地圖,表格等。 我們不可能將它們?nèi)苛谐?,所以下面列出的是個中的翹楚。

        matplotlib (http://matplotlib.sourceforge.net/) 可以用于生成通常是由 matlab 或者 Mathematica 生成的高質(zhì)量圖表。

        pygraphviz (https://networkx.lanl.gov/wiki/pygraphviz) 是一個 Graphviz 圖形布局的工具 (http://graphviz.org/) 的 Python 接口,可以用于生成結(jié)構(gòu)化的圖表和網(wǎng)絡(luò)。

總之,所有可以寫文件的庫都可以與 Django 同時使用。 The possibilities are immense.

我們已經(jīng)了解了生成“非HTML”內(nèi)容的基本知識,讓我們進一步總結(jié)一下。 Django擁有很多用以生成各類“非HTML”內(nèi)容的內(nèi)置工具。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 庐江县| 若尔盖县| 绥化市| 百色市| 诸暨市| 舟曲县| 嵩明县| 连平县| 科技| 肥西县| 明星| 钦州市| 开阳县| 江门市| 陆川县| 徐汇区| 隆林| 潍坊市| 偏关县| 乌海市| 油尖旺区| 和静县| 和田县| 华宁县| 东乌珠穆沁旗| 上高县| 神木县| 邯郸市| 罗田县| 宁夏| 拜城县| 禄劝| 静海县| 皮山县| 潍坊市| 甘肃省| 江源县| 蕲春县| 万源市| 葫芦岛市| 汉源县|