在生成PDF报表时,往往需要动态的生成表格和一些折线图、饼状图等,利用RML文件和reportlab的api来动态生成。
表格
利用<blockTable>
和<blockTableStyle>
,生成有多种样式的表格,并通过内嵌python代码来动态的填充数据。
统计图
官网chart gallery 下有很多的统计图的举例,都有源码,地址为 https://www.reportlab.com/chartgallery/line/ ,展示了如何利用API构造生成一个统计图表的PDF。利用RML中的<drawing>
标签,在PDF中动态的添加统计图,参考RML Samples下的http://www.reportlab.com/examples/rml/test/test_014_graphics.pdf 。
-
<drawing>
:通过查看Tag Reference发现该标签拥有module
和function
两个属性。module
所对应的即py的module,function
是该module下的类(或方法)。 -
class DemoDrawing(_DrawingEditorMixin, Drawing)
:仿照官网的统计图的Demo,编写定义统计图Drawing的类。 -
<param name=''>
:利用<drawing></drawing>
下的<param>
标签和其name
属性指定统计图所需参数,同时结合RML中的{{}}
,动态的填充参数数据。
结合官网的QuickChart的Demo编写一个简单的生成统计图PDF的ChartDemo。
- 简单生成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```
* 统计图Drawing类```charts_model.py```:该类利用```QuickChart```快速生成了一个柱状图。
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">测试统计图</para>
<drawing module="charts_model" function="QuickDemoDrawing"></drawing>
</story>
</document>
* 动态填充数据:如现在需要动态的往```charts_demo.rml```所生成的PDF文件中添加统计图所需的数据或者定制不同统计图的大小等其他属性。
* 仿照官网Basic Pie编写Drawing类(或方法),并注释了部分填充数据的代码:
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>```,并内嵌python代码使能够动态的获取数据:
<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时传入需要的数据:
if name == 'main':
# 模板文件
template = 'charts_demo'
# 输出的pdf
output_filename = 'output/' + template + '.pdf'
# 数据
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()