Code snippets are bits of re-usable code submitted by the ReportLab community. We don't promise that they are accurate, up-to-date or correct - use them at your own risk!

We'd love it if you could participate by submitting your own snippets and sharing your experience with others by commenting. You will need to create a user account by filling out our very simple form.

View all snippets


Alpha Colours (transparency)
opensourcerl-toolkit

pix/RLIMG_4e80749b9c07077da1c02224f703a217.PNG
Author:
rptlab
Posted:
11 Dec 2009
Language:
Python
Tags:
opensource rl-toolkit

In 2009 we added support for alpha (transparency). This works by specifying an 'alpha' value for each colour, as well as traditional red, green and blue. By default, alpha is 1.0 (i.e. not transparent).

This snippet shows two cases of rectangles overlapping. The first case uses solid colours so the red rectangle hides the one underneath it. The second case uses transparent colours so that you can see the blue rectangle through the red one.

Alpha is intended for use with RGB colours. For transparency effects in professional printing and the CMYK world, we'll publish another technique soon.

"""
A simple usage of alpha (transparent) colours
"""
from reportlab.graphics.shapes import Rect
from reportlab.pdfgen.canvas import Canvas
from reportlab.lib.colors import PCMYKColor, PCMYKColorSep, Color, black, blue, red

filename = 'alpha.pdf'

red50transparent = Color( 100, 0, 0, alpha=0.5)

c = Canvas(filename,pagesize=(400,200))
c.setFillColor(black)
c.setFont('Helvetica', 10)

c.drawString(25,180, 'solid')
c.setFillColor(blue)
c.rect(25,25,100,100, fill=True, stroke=False)
c.setFillColor(red)
c.rect(100,75,100,100, fill=True, stroke=False)

c.setFillColor(black)
c.drawString(225,180, 'transparent')

c.setFillColor(blue)
c.rect(225,25,100,100, fill=True, stroke=False)
c.setFillColor(red50transparent)
c.rect(300,75,100,100, fill=True, stroke=False)

c.save()