Chinaunix首页 | 论坛 | 博客
  • 博客访问: 56245
  • 博文数量: 13
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 199
  • 用 户 组: 普通用户
  • 注册时间: 2014-03-07 22:11
文章分类

全部博文(13)

文章存档

2014年(13)

我的朋友

分类: Python/Ruby

2014-04-09 21:44:28

1.环境搭建
    介绍基于Python平台的优秀PDF报表类库Reportlab。它不属于Python的标准类库,所以必须手动下载类库包并安装。因为涉及到把图片转换为PDF,所以还需要Python imaging library(PIL)类库。两个类库下载地址:

    ReportLab:
    Python Imaging Library:

    目前ReprtLab只有支持Python2.X版本,估计3.x版本的也很快放出。安装方法:windows用户可以直接下载.exe安装包,直接安装。如果是linux用户,可以下载源码安装(建议先安装PIL包)。安装方法(需要把安装代码放在python安装目录的合适位置):

# python setup.py install

安装之后可以运行自带例子,通常放在Lib/site-packages/reportlab/test的目录下,
#python setup.py tests
测试是否安装成功

2.代码实现
 ---------hello_report.py
  1 #!/usr/bin/env python
  2
  3 from reportlab.graphics.shapes import Drawing,String
  4 from reportlab.graphics import renderPDF
  5
  6 d=Drawing(100,100)
  7 s=String(50,50,'hello,world',textAnchor='middle')
  8
  9 d.add(s)
 10
 11 renderPDF.drawToFile(d,'hello.pdf','a simple pdf file')


真正的实现,抓取空间天气预报中心的网页,提取数据绘制成图,用reportlab模块
--------sunpots_report.py
  1 #!/usr/bin/env python
  2 from urllib import urlopen
  3 from reportlab.graphics.shapes import *
  4 from reportlab.graphics.charts.lineplots import LinePlot
  5 from reportlab.graphics.charts.textlabels import Label
  6 from reportlab.graphics import renderPDF
  7
  8 URL=''
  9
 10 COMMENT_CHARS='#:'
 11
 12 drawing=Drawing(400,200)
 13 data=[]
 14 for line in urlopen(URL).readlines():
 15     if not line.isspace() and not line[0] in COMMENT_CHARS:
 16         data.append([float(n) for n in line.split()])
 17
 18 pred=[row[2] for row in data]
 19 high=[row[3] for row in data]
 20 low=[row[4] for row in data]
 21 times=[row[0]+row[1]/12.0 for row in data]
 22
 23 lp=LinePlot()
 24 lp.x=50
 25 lp.y=50
 26 lp.height=125
 27 lp.width=300
 28 lp.data=[zip(times,pred),zip(times,high),zip(times,low)]
 29 lp.lines[0].strokeColor=colors.blue
 30 lp.lines[1].strokeColor=colors.red
 31 lp.lines[2].strokeColor=colors.green
 32
 33 drawing.add(lp)
 34 drawing.add(String(250,150,'sunspots',fontSize=14,fillColor=colors.red))
 35
 36 renderPDF.drawToFile(drawing,'report2.pdf','sunspots')

生成PDF在下

report2.pdf

具体代码解释参见python基础教程,博主现在也是新手,只能实现下代码咯

阅读(3925) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~