Search code examples
pythonpdf-generationreportlab

How to set the text color of a textobject using reportlab pdfgen


I was recently looking for the function needed to set a textobject's text color. The textobject is a specific method of working with reportlab's pdfgen. The documentation has some information, but it's pretty unclear.

Starting code:

textobject = canvas.beginText()
textobject.textOut("Example Text")
canvas.drawText(textobject)

Solution

  • Use the setFillColorRGB() function to change the color. The function takes 3 values (red, green, blue) and expects the values to be 0-1.

    Example:

    textobject = canvas.beginText()
    textobject.setFillColorRGB(0.5, 0.5, 0.5) #grey text
    textobject.textOut("Example Text")
    canvas.drawText(textobject)