来源:http://blog.csdn.net/happyteafriends/article/details/9418341
转载原因:直接复制代码碰到点问题,等下记录下
官方介绍:
Generating PDFs from Wall Street to Wikipedia
We build solutions to generate rich, attractive and fully bespoke PDF documents at incredible speeds. This can let you serve personalised documents in real time, produce high-quality output, and support all kinds of delivery from web downloads through to personalised digital print.
简要来说,就是 快速实时生成丰富的、定制的PDF文档。用于实时个性化定制,生成高质量的输出,支持各种交付,可以从网络下载到个人输出等。
安装:
- # yum install freetype-devel.x86_64
- # yum install python-devel.x86_64
- # pip install reportlab
- # error: command 'gcc' failed with exit status 1 Command /usr/bin/python -c "import setuptools;__file__='/tmp/pip-build-root/reportlab/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-oneoII-record/install-record.txt --single-version-externally-managed failed with error code 1 in /tmp/pip-build-root/reportlab
几个例子:
坐标图:
- from reportlab.lib import colors
- from urllib import urlopen
- from reportlab.graphics.shapes import *
- from reportlab.graphics.charts.lineplots import LinePlot
- from reportlab.graphics import renderPDF
- URL="http://www.swpc.noaa.gov/ftpdir/weekly/Predict.txt"
- COMMENT_CHARS='#:'
- drawing = Drawing(400,200)
- data = []
- for line in urlopen(URL).readlines():
- if not line.isspace() and not line[0] in COMMENT_CHARS:
- data.append([float(n) for n in line.split()])
- pred = [row[2] for row in data]
- high = [row[3] for row in data]
- low = [row[4] for row in data]
- times = [row[0] + row[1]/12.0 for row in data]
- lp = LinePlot()
- lp.x = 50
- lp.y = 50
- lp.height = 125
- lp.width = 300
- lp.data = [zip(times,pred),zip(times,high),zip(times,low)]
- drawing.add(lp)
- renderPDF.drawToFile(drawing,'report.pdf','Sunspots')
- def main():
- return 0
- if __name__ == '__main__':
- main()
坐标柱状图:
- from reportlab.lib.colors import Color, blue, red
- from reportlab.graphics.charts.legends import Legend, TotalAnnotator
- from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin
- from standard_colors import pdf_chart_colors, setItems
- from reportlab.lib.validators import Auto
- from reportlab.graphics.charts.barcharts import VerticalBarChart
- class FactSheetHoldingsVBar(_DrawingEditorMixin,Drawing):
- def __init__(self,width=400,height=200,*args,**kw):
- apply(Drawing.__init__,(self,width,height)+args,kw)
- self._add(self,VerticalBarChart(),name='bar',validate=None,desc=None)
- self.bar.data = [[4.22], [4.12], [3.65], [3.56], [3.49], [3.44], [3.07], [2.84], [2.76], [1.09]]
- self.bar.categoryAxis.categoryNames = ['Financials','Energy','Health Care','Telecoms','Consumer','Consumer 2','Industrials','Materials','Other','Liquid Assets']
- self.bar.categoryAxis.labels.fillColor = None
- self.bar.width = 200
- self.bar.height = 150
- self.bar.x = 30
- self.bar.y = 15
- self.bar.barSpacing = 5
- self.bar.groupSpacing = 5
- self.bar.valueAxis.labels.fontName = 'Helvetica'
- self.bar.valueAxis.labels.fontSize = 8
- self.bar.valueAxis.forceZero = 1
- self.bar.valueAxis.rangeRound = 'both'
- self.bar.valueAxis.valueMax = None#10#
- self.bar.categoryAxis.visible = 1
- self.bar.categoryAxis.visibleTicks = 0
- self.bar.barLabels.fontSize = 6
- self.bar.valueAxis.labels.fontSize = 6
- self.bar.strokeWidth = 0.1
- self.bar.bars.strokeWidth = 0.5
- n = len(self.bar.data)
- setItems(n,self.bar.bars,'fillColor',pdf_chart_colors)
- #add and set up legend
- self._add(self,Legend(),name='legend',validate=None,desc=None)
- _ = ['Vodafone Group', 'UBS', 'British Petroleum', 'Royal bk of Scotland', 'HSBC Holdings', 'Total Elf Fina', 'Repsol', 'Novartis', 'BNP Paribas', 'Schneider Electric' ]
- self.legend.colorNamePairs = [(Auto(chart=self.bar),(t,'%.2f'% d[0])) for t,d in zip(_,self.bar.data)]
- self.legend.columnMaximum = 10
- self.legend.fontName = 'Helvetica'
- self.legend.fontSize = 5.5
- self.legend.boxAnchor = 'w'
- self.legend.x = 260
- self.legend.y = self.height/2
- self.legend.dx = 8
- self.legend.dy = 8
- self.legend.alignment = 'right'
- self.legend.yGap = 0
- self.legend.deltay = 11
- self.legend.dividerLines = 1|2|4
- self.legend.subCols.rpad = 10
- self.legend.dxTextSpace = 5
- self.legend.strokeWidth = 0
- self.legend.dividerOffsY = 6
- self.legend.colEndCallout = TotalAnnotator(rText='%.2f'%sum([x[0] for x in self.bar.data]), fontName='Helvetica-Bold', fontSize=self.legend.fontSize*1.1)
- self.legend.colorNamePairs = [(self.bar.bars[i].fillColor, (self.bar.categoryAxis.categoryNames[i][0:20], '%0.2f' % self.bar.data[i][0])) for i in range(len(self.bar.data))]
- def main():
- drawing = FactSheetHoldingsVBar()
- drawing.save(formats=['pdf'],outDir='.',fnRoot=None)
- drawing.save(formats=['png'],outDir='.',fnRoot=None)
- return 0
- if __name__ == '__main__':
- main()
绘制饼图:
- from reportlab.graphics.charts.piecharts import Pie
- from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin
- from reportlab.lib.colors import Color, magenta, cyan
- class pietests(_DrawingEditorMixin,Drawing):
- def __init__(self,width=400,height=200,*args,**kw):
- Drawing.__init__(self,width,height,*args,**kw)
- self._add(self,Pie(),name='pie',validate=None,desc=None)
- self.pie.sideLabels = 1
- self.pie.labels = ['Label 1', 'Label 2', 'Label 3', 'Label 4', 'Label 5']
- self.pie.data = [20, 10, 5, 5, 5]
- self.pie.width = 140
- self.pie.height = 140
- self.pie.y = 35
- self.pie.x = 125
- def main():
- drawing = pietests()
- # you can do all sorts of things to drawing, lets just save it as pdf and png.
- drawing.save(formats=['pdf','png'],outDir='.',fnRoot=None)
- return 0
- if __name__ == '__main__':
- main()
效果:
官网:
文档:
http://www.reportlab.com/software/documentation/
示例:
http://www.reportlab.com/snippets/