在生成PDF報(bào)表時(shí)进每,往往需要?jiǎng)討B(tài)的生成表格和一些折線圖麻顶、餅狀圖等洗出,利用RML文件和reportlab的api來動(dòng)態(tài)生成镀娶。
表格
利用<blockTable>
和<blockTableStyle>
,生成有多種樣式的表格变骡,并通過內(nèi)嵌python代碼來動(dòng)態(tài)的填充數(shù)據(jù)护昧。
統(tǒng)計(jì)圖
官網(wǎng)chart gallery 下有很多的統(tǒng)計(jì)圖的舉例庄拇,都有源碼倍啥,地址為 https://www.reportlab.com/chartgallery/line/ 禾乘,展示了如何利用API構(gòu)造生成一個(gè)統(tǒng)計(jì)圖表的PDF。利用RML中的<drawing>
標(biāo)簽虽缕,在PDF中動(dòng)態(tài)的添加統(tǒng)計(jì)圖始藕,參考RML Samples下的http://www.reportlab.com/examples/rml/test/test_014_graphics.pdf 。
-
<drawing>
:通過查看Tag Reference發(fā)現(xiàn)該標(biāo)簽擁有module
和function
兩個(gè)屬性氮趋。module
所對(duì)應(yīng)的即py的module伍派,function
是該module下的類(或方法)。 -
class DemoDrawing(_DrawingEditorMixin, Drawing)
:仿照官網(wǎng)的統(tǒng)計(jì)圖的Demo剩胁,編寫定義統(tǒng)計(jì)圖Drawing的類诉植。 -
<param name=''>
:利用<drawing></drawing>
下的<param>
標(biāo)簽和其name
屬性指定統(tǒng)計(jì)圖所需參數(shù),同時(shí)結(jié)合RML中的{{}}
昵观,動(dòng)態(tài)的填充參數(shù)數(shù)據(jù)倍踪。
結(jié)合官網(wǎng)的QuickChart的Demo編寫一個(gè)簡(jiǎn)單的生成統(tǒng)計(jì)圖PDF的ChartDemo。
- 簡(jiǎn)單生成PDF工具類
utils.py
:
from rlextra.rml2pdf import rml2pdf
import preppy
from io import BytesIO
class PDFUtils(object):
def __init__(self, template_name, namespace, output_filename=None):
self.template_name = template_name
self.namespace = namespace
self.output_filename = output_filename
def create_pdf(self):
source_text = open(self.template_name, 'r', encoding='utf-8').read()
template = preppy.getModule(self.template_name, sourcetext=source_text)
rml = template.getOutput(self.namespace)
if self.output_filename:
rml2pdf.go(rml.encode('utf-8'), outputFileName=self.output_filename)
return True
else:
buf = BytesIO()
rml2pdf.go(rml.encode('utf-8'), outputFileName=buf)
pdf_data = buf.getvalue()
return pdf_data```
* 統(tǒng)計(jì)圖Drawing類```charts_model.py```:該類利用```QuickChart```快速生成了一個(gè)柱狀圖索昂。
from rlextra.graphics.quickchart import QuickChart
from reportlab.lib.corp import white, black
from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin
class QuickDemoDrawing(_DrawingEditorMixin, Drawing):
def init(self, width=400, height=200, *args, **kw):
Drawing.init(self, width, height, *args, **kw)
self._add(self, QuickChart(), name='chart', validate=None, desc=None)
self.chart.x = 100
self.chart.y = 300
self.chart.height = 200
self.chart.seriesNames = 'a', 'b', 'c'
self.chart.seriesRelation = None
self.chart.dataLabelsFontSize = 12
self.chart.chartSeparation = 1
self.chart.data = [[100, 120, 140], [110, 130, 150], [200, 100, 100]]
self.chart.chartType = 'column'
self.chart.titleText = 'Column Chart'
self.chart.xTitleText = ''
self.chart.categoryNames = ('2009', '2010', '2012')
self.chart.pointerLabelMode = 'leftAndRight'
self.chart.bgColor = 'white'
self.chart.plotColor = white
self.chart.titleFontColor = black
* .rml文件```charts_demo.rml```:
<?xml version="1.0" encoding="utf-8" standalone="no" ?>
<!DOCTYPE document SYSTEM "rml.dtd">
<document filename="charts_demo.pdf">
<docinit useCropMarks="0">
<registerTTFont faceName="song" fileName="STSONG.TTF"/>
</docinit>
<template pageSize="A4" showBoundary="1" title="test_demo" author="JiangW">
<pageTemplate id="common_page_template_1">
<pageGraphics>
<setFont name="Helvetica-Bold" size="18"/>
<drawString x="250" y="300"><pageNumber/></drawString>
<image file="logo_no_bar.png" preserveAspectRatio="1" x="1in" y="749" width="72" height="72"/>
<image file="strapline.png" preserveAspectRatio="1" x="1in" y="0"/>
</pageGraphics>
<frame id="common_frame_1" x1="1in" y1="1in" width="450" height="9in"/>
</pageTemplate>
</template>
<stylesheet>
<paraStyle name="song" fontName="song" fontSize="12" leading="12"/>
</stylesheet>
<story firstPageTemplate="common_page_template_1">
<para style="song">測(cè)試統(tǒng)計(jì)圖</para>
<drawing module="charts_model" function="QuickDemoDrawing"></drawing>
</story>
</document>
* 動(dòng)態(tài)填充數(shù)據(jù):如現(xiàn)在需要?jiǎng)討B(tài)的往```charts_demo.rml```所生成的PDF文件中添加統(tǒng)計(jì)圖所需的數(shù)據(jù)或者定制不同統(tǒng)計(jì)圖的大小等其他屬性。
* 仿照官網(wǎng)Basic Pie編寫Drawing類(或方法)扩借,并注釋了部分填充數(shù)據(jù)的代碼:
class PieChartDrawing(_DrawingEditorMixin, Drawing):
def init(self, width=400, height=200, *args, **kw):
Drawing.init(self, width, height, *args, **kw)
fontSize = 8
fontName = 'Helvetica'
# pie
self._add(self, Pie(), name='pie', validate=None, desc=None)
self.pie.strokeWidth = 1
self.pie.slices.strokeColor = PCMYKColor(0, 0, 0, 0)
self.pie.slices.strokeWidth = 1
# legend
self._add(self, Legend(), name='legend', validate=None, desc=None)
self.legend.columnMaximum = 99
self.legend.alignment = 'right'
self.legend.dx = 6
self.legend.dy = 6
self.legend.dxTextSpace = 5
self.legend.deltay = 10
self.legend.strokeWidth = 0
self.legend.subCols[0].minWidth = 75
self.legend.subCols[0].align = 'left'
self.legend.subCols[1].minWidth = 25
self.legend.subCols[1].align = 'right'
# sample data
# colors = [PCMYKColor(100, 67, 0, 23, alpha=100), PCMYKColor(70, 46, 0, 16, alpha=100), PCMYKColor(50, 33, 0, 11, alpha=100), PCMYKColor(30, 20, 0, 7, alpha=100), PCMYKColor(20, 13, 0, 4, alpha=100), PCMYKColor(
# 10, 7, 0, 3, alpha=100), PCMYKColor(0, 0, 0, 100, alpha=100), PCMYKColor(0, 0, 0, 70, alpha=100), PCMYKColor(0, 0, 0, 50, alpha=100), PCMYKColor(0, 0, 0, 30, alpha=100), PCMYKColor(0, 0, 0, 20, alpha=100), PCMYKColor(0, 0, 0, 10, alpha=100)]
# self.pie.data = [56.0, 12.199999999999999, 28.5, 3.3999999999999999]
# for i in range(len(self.pie.data)):
# self.pie.slices[i].fillColor = colors[i]
self.height = 200
self.legend.boxAnchor = 'c'
self.legend.y = 100
self.pie.strokeColor = PCMYKColor(0, 0, 0, 0, alpha=100)
# self.pie.slices[1].fillColor = PCMYKColor(100, 60, 0, 50, alpha=100)
# self.pie.slices[2].fillColor = PCMYKColor(0, 100, 100, 40, alpha=100)
# self.pie.slices[3].fillColor = PCMYKColor(66, 13, 0, 22, alpha=100)
# self.pie.slices[0].fillColor = PCMYKColor(100, 0, 90, 50, alpha=100)
# self.legend.colorNamePairs = [(PCMYKColor(100, 0, 90, 50, alpha=100), ('BP', '56.0%')), (PCMYKColor(100, 60, 0, 50, alpha=100), ('BT', '12.2%')), (PCMYKColor(
# 0, 100, 100, 40, alpha=100), ('Tesco', '28.5%')), (PCMYKColor(66, 13, 0, 22, alpha=100), ('Persimmon', '3.4%'))]
self.width = 400
self.legend.x = 350
self.pie.width = 150
self.pie.height = 150
self.pie.y = 25
self.pie.x = 25
* 在```charts_demo.rml```中添加```<drawing>```椒惨,并內(nèi)嵌python代碼使能夠動(dòng)態(tài)的獲取數(shù)據(jù):
<drawing module="charts_model" function="PieChartDrawing">
<param name="pie.data">{{common_pie['pie_data']}}</param>
<param name="legend.colorNamePairs">{{common_pie['legend_colorNamePairs']}}</param>
{{for i, v in enumerate(common_pie['pie_data'])}}
<param name="pie.slices[{{i}}].fillColor">{{common_pie['colors'][i]}}</param>
{{endfor}}
</drawing>
* 在生成PDF時(shí)傳入需要的數(shù)據(jù):
if name == 'main':
# 模板文件
template = 'charts_demo'
# 輸出的pdf
output_filename = 'output/' + template + '.pdf'
# 數(shù)據(jù)
quick_pie = {
'chartType': 'pie',
'titleText': 'Quick Pie',
'categoryNames': ('2013', '2014', '2015', '2016')
}
from reportlab.lib.colors import Color, PCMYKColor, white
common_pie = {
'colors': [PCMYKColor(100, 0, 90, 50, alpha=100), PCMYKColor(100, 60, 0, 50, alpha=100), PCMYKColor(0, 100, 100, 40, alpha=100), PCMYKColor(66, 13, 0, 22, alpha=100)],
'pie_data': [56.0, 12.199999999999999, 28.5, 3.3999999999999999],
'legend_colorNamePairs': [(PCMYKColor(100, 0, 90, 50, alpha=100), ('BP', '56.0%')), (PCMYKColor(100, 60, 0, 50, alpha=100), ('BT', '12.2%')), (PCMYKColor(0, 100, 100, 40, alpha=100), ('Tesco', '28.5%')), (PCMYKColor(66, 13, 0, 22, alpha=100), ('Persimmon', '3.4%'))],
}
namespace = {
'quick_pie': quick_pie,
'common_pie': common_pie
}
p = PDFUtils(template + '.rml', namespace, output_filename=output_filename)
p.create_pdf()