跳转至

编写自定义 Flowable 对象

Flowable 旨在成为创建可复用报表内容的开放标准, 您可以轻松创建自己的对象。我们希望随着时间的推移, 能够建立起一个贡献库,为 ReportLab 用户提供丰富的图表、 图形和其他"报表小部件"供其在自己的报表中使用。 本节将向您展示如何创建自己的 Flowable。

TODO: 我们应该将 Figure 类放入标准库中, 因为它是一个非常实用的基类。

10.1 一个非常简单的 Flowable

回顾本用户指南 pdfgen 章节中的 hand 函数, 它生成了一个由贝塞尔曲线组合而成的手的封闭图形。

要将此绘图或任何其他绘图嵌入到 Platypus Flowable 中,我们必须定义一个 Flowable 的子类, 至少包含一个 wrap 方法和一个 draw 方法。

from reportlab.platypus.flowables import Flowable
from reportlab.lib.colors import tan, green
class HandAnnotation(Flowable):
    '''A hand flowable.'''
    def __init__(self, xoffset=0, size=None, fillcolor=tan, strokecolor=green):
        from reportlab.lib.units import inch
        if size is None: size=4*inch
        self.fillcolor, self.strokecolor = fillcolor, strokecolor
        self.xoffset = xoffset
        self.size = size
        # normal size is 4 inches
        self.scale = size/(4.0*inch)
    def wrap(self, *args):
        return (self.xoffset, self.size)
    def draw(self):
        canvas = self.canv
        canvas.setLineWidth(6)
        canvas.setFillColor(self.fillcolor)
        canvas.setStrokeColor(self.strokecolor)
        canvas.translate(self.xoffset+self.size,0)
        canvas.rotate(90)
        canvas.scale(self.scale, self.scale)
        hand(canvas, debug=0, fill=1)

wrap 方法必须提供绘图的尺寸——Platypus 主循环用它来决定该元素是否适合当前框架中的剩余空间。 draw 方法在 Platypus 主循环将 (0,0) 原点平移到相应框架中的适当位置后执行对象的绘制。

下面是 HandAnnotation Flowable 的一些使用示例。

默认设置。

仅一英寸高。

一英寸高,向左偏移,使用蓝色和青色。

10.2 修改内置 Flowable

要修改现有的 Flowable,您应该创建一个派生类, 并重写需要更改的方法以获得所需的行为。

例如,要创建旋转图像,您需要重写现有 Image 类的 wrap 和 draw 方法。

class RotatedImage(Image):
    def wrap(self,availWidth,availHeight):
        h, w = Image.wrap(self,availHeight,availWidth)
        return w, h
    def draw(self):
        self.canv.rotate(90)
        Image.draw(self)
I = RotatedImage('../images/replogo.gif')
I.hAlign = 'CENTER'

Produces: