Colored ReportLab Frames
July 23, 2012I'm currently working on improving the style of a medical report where I need to create colored ReportLab frames. I found someone else wondering if it's possible but no code example. So I wrote my own.
The original question: http://two.pairlist.net/pipermail/reportlab-users/2008-January/006654.html
The source code for the frame class: https://github.com/ejucovy/reportlab/blob/master/src/reportlab/platypus/frames.py
My implementation:
from reportlab.lib.colors import toColor class ColorFrame(Frame): """ Extends the reportlab Frame with a background color. """ def __init__(self, *args, **kwargs): self.background = kwargs.pop('background') super().__init__(*args, **kwargs) def drawBackground(self, canv): color = toColor(self.background) canv.saveState() canv.setFillColor(color) canv.rect( self._x1, self._y1, self._x2 - self._x1, self._y2 - self._y1, stroke=0, fill=1 ) canv.restoreState() def addFromList(self, drawlist, canv): if self.background: self.drawBackground(canv) Frame.addFromList(self, drawlist, canv)
With this example it is possible to do something like that:
f = ColorFrame(background='#0000ff') f.addFromList(elements, canvas)
To get a frame with blue background.