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


Posted in Python onJuly 22, 2015

便携文档格式 (PDF) 是由 Adobe 开发的格式,主要用于呈现可打印的文档,其中包含有 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) 。动态生成 PDF 文件的好处是在不同的情况下,如不同的用户或者不同的内容,可以按需生成不同的 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 发行版,则在安装前可以先检查包管理软件。 多数软件包仓库中都加入了 ReportLab 。

比如,如果使用(杰出的) Ubuntu 发行版,只需要简单的 apt-get install python-reportlab 一行命令即可完成安装。

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

在 Python 交互环境中导入这个软件包以检查安装是否成功。

>>> import reportlab

如果刚才那条命令没有出现任何错误,则表明安装成功。
编写视图

和 CSV 类似,由 Django 动态生成 PDF 文件很简单,因为 ReportLab API 同样可以使用类似文件对象。

下面是一个 Hello World 的示例:

from reportlab.pdfgen import canvas
from django.http import HttpResponse

def 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 文档。 如果忽略了这个参数,浏览器可能会把这个文件看成 HTML 文档,这会使浏览器的窗口中出现很奇怪的文字。 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 的第一个参数传入。

    所有后续的 PDF 生成方法需要由 PDF 对象调用(在本例中是 p ),而不是 response 对象。

    最后需要对 PDF 文件调用 showPage() 和 save() 方法(否则你会得到一个损坏的 PDF 文件)。

复杂的 PDF 文件

如果您在创建一个复杂的 PDF 文档(或者任何较大的数据块),请使用 cStringIO 库存放临时生成的 PDF 文件。 cStringIO 提供了一个用 C 编写的类似文件对象的接口,从而可以使系统的效率最高。

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

from cStringIO import StringIO
from reportlab.pdfgen import canvas
from django.http import HttpResponse

def 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 可以生成许多其它类型的内容,下面介绍的是一些其它的想法和一些可以用以实现它们的库。 Here are a few more ideas and some pointers to libraries you could use to implement them:

    ZIP 文件 :Python 标准库中包含有 zipfile 模块,它可以读和写压缩的 ZIP 文件。 它可以用于按需生成一些文件的压缩包,或者在需要时压缩大的文档。 如果是 TAR 文件则可以使用标准库 tarfile 模块。

    动态图片 : Python 图片处理库 (PIL; http://www.pythonware.com/products/pil/) 是极好的生成图片(PNG, JPEG, GIF 以及其它许多格式)的工具。 它可以用于自动为图片生成缩略图,将多张图片压缩到单独的框架中,或者是做基于 Web 的图片处理。

    图表 : Python 有许多出色并且强大的图表库用以绘制图表,按需地图,表格等。 我们不可能将它们全部列出,所以下面列出的是个中的翘楚。

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

        pygraphviz (https://networkx.lanl.gov/wiki/pygraphviz) 是一个 Graphviz 图形布局的工具 (http://graphviz.org/) 的 Python 接口,可以用于生成结构化的图表和网络。

总之,所有可以写文件的库都可以与 Django 同时使用。 The possibilities are immense.

我们已经了解了生成“非HTML”内容的基本知识,让我们进一步总结一下。 Django拥有很多用以生成各类“非HTML”内容的内置工具。

Python 相关文章推荐
详解python多线程、锁、event事件机制的简单使用
Apr 27 Python
linux下python使用sendmail发送邮件
May 22 Python
利用Python将数值型特征进行离散化操作的方法
Nov 06 Python
python django 原生sql 获取数据的例子
Aug 14 Python
在Django中预防CSRF攻击的操作
Mar 13 Python
520使用Python实现“我爱你”表白
May 20 Python
Python通过文本和图片生成词云图
May 21 Python
Python astype(np.float)函数使用方法解析
Jun 08 Python
sublime3之内网安装python插件Anaconda的流程
Nov 10 Python
pytorch锁死在dataloader(训练时卡死)
May 28 Python
用Python实现一个打字速度测试工具来测试你的手速
May 28 Python
通过Python把学姐照片做成拼图游戏
Feb 15 Python
在Python的Django框架中生成CSV文件的方法
Jul 22 #Python
在主机商的共享服务器上部署Django站点的方法
Jul 22 #Python
在Lighttpd服务器中运行Django应用的方法
Jul 22 #Python
简单的Apache+FastCGI+Django配置指南
Jul 22 #Python
使用FastCGI部署Python的Django应用的教程
Jul 22 #Python
使用相同的Apache实例来运行Django和Media文件
Jul 22 #Python
在Apache服务器上同时运行多个Django程序的方法
Jul 22 #Python
You might like
短波的认识
2021/03/01 无线电
php面象对象数据库操作类实例
2014/12/02 PHP
利用laravel+ajax实现文件上传功能方法示例
2017/08/13 PHP
PHP基于curl post实现发送url及相关中文乱码问题解决方法
2017/11/25 PHP
Javascript hasOwnProperty 方法 & in 关键字
2008/11/26 Javascript
JavaScript面向对象(极简主义法minimalist approach)
2012/07/17 Javascript
jquery实现带复选框的表格行选中删除时高亮显示
2013/08/01 Javascript
ExtJS4如何给同一个formpanel不同的url
2014/05/02 Javascript
按钮接受回车事件的三种实现方法
2014/06/06 Javascript
JS常见问题之为什么点击弹出的i总是最后一个
2016/01/05 Javascript
详解WordPress开发中get_current_screen()函数的使用
2016/01/11 Javascript
JavaScript焦点事件、鼠标事件和滚轮事件使用详解
2016/01/15 Javascript
用js读写cookie的简单方法(推荐)
2016/08/08 Javascript
网页瀑布流布局jQuery实现代码
2016/10/21 Javascript
Vue2.0学习之详解Vue 组件及父子组件通信
2017/12/12 Javascript
官方推荐react-navigation的具体使用详解
2018/05/08 Javascript
一个Java程序猿眼中的前后端分离以及Vue.js入门(推荐)
2019/04/19 Javascript
Vue 无限滚动加载指令实现方法
2019/05/28 Javascript
bootstrap Table实现合并相同行
2019/07/19 Javascript
浅谈vue项目用到的mock数据接口的两种方式
2019/10/09 Javascript
如何利用 JS 脚本实现网页全自动秒杀抢购功能
2020/10/12 Javascript
[01:09]模型精美,特效酷炫!TI9不朽宝藏Ⅰ鉴赏
2019/05/10 DOTA
python引入不同文件夹下的自定义模块方法
2018/10/27 Python
python实现操作文件(文件夹)
2019/10/31 Python
Pytorch在NLP中的简单应用详解
2020/01/08 Python
Python数据相关系数矩阵和热力图轻松实现教程
2020/06/16 Python
Python导入父文件夹中模块并读取当前文件夹内的资源
2020/11/19 Python
详解Python GUI编程之PyQt5入门到实战
2020/12/10 Python
非常漂亮的CSS3百叶窗焦点图动画
2016/02/24 HTML / CSS
澳大利亚潮流尖端的快时尚品牌:Cotton On
2016/09/26 全球购物
GANT英国官方网上商店:甘特衬衫
2018/02/06 全球购物
法律进学校实施方案
2014/03/15 职场文书
质量月口号
2014/06/20 职场文书
挂职学习心得体会
2014/09/09 职场文书
化工厂员工工作总结
2015/10/15 职场文书
解决linux下redis数据库overcommit_memory问题
2022/02/24 Redis