Is it possible to create a gradient fill in a PDF using ReportLab (python)?
Use setFillColorRBG
:
c.setFillColorRGB(0,0,0) # black fill
c.rect(200, 278, 121, 12, stroke=0, fill=1)
c.setFont(Helvetica_Bold_Oblique, 10)
c.setStrokeColorRGB(1,1,1) # white text
c.setFillColorRGB(1,1,1) # white text
c.drawString(202, 280, 'DUE FROM PATIENT')
c.restoreState()
Sorry to ressurect this question, but I stumbled across it and it hadn't been correctly answered.
The answer is no, as of today, the current version of ReportLab does not support gradients. Gradients are supported by PDF, however. If you look in ReportLab's Canvas class you'll see that many of its methods are relatively small wrappers around the underlying PDF code generation. To access gradients in RL you'd need to extend the Canvas class and add additional methods to generate the correct PDF code. This is doable, but obviously not trivial, and it means you'd have to read up on the PDF spec.
There are two alternatives. Firstly generate the gradient as a raster image and use that, secondly generate the gradient by drawing a whole series of rectangles in different colors.
start_color = (1,0,0)
end_color = (0,1,0)
for i in range(100):
p = i * 0.01
canvas.setFillColorRGB(*[start_color[i]*(1.0-p)+end_color[i]*p for i in range(3)])
canvas.rect(i, 0, 2, 100)
For example. Unfortunately getting the gradient smooth takes a lot of rectangles, and this can cause the PDF to be large and render slowly. You're better off with the raster approach.
Finally, you might consider using PyCairo. This has better support for lots of graphical elements, and can render to a PDF or PNG. It lacks reportlabs higher lever constructs (such as page layout), however.