Python – How to use hexadecimal color values in Python ReportLab PDF generation

How to use hexadecimal color values in Python ReportLab PDF generation… here is a solution to the problem.

How to use hexadecimal color values in Python ReportLab PDF generation

I’m trying to generate a multi-page pdf document, reading some py files and other doc files. I’m trying to do this using SimpleDocTemplate instead of Canvas. Now I want to color the text with hexadecimal values. I tried the following:

from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate
from reportlab.platypus.para import Paragraph
from reportlab.lib.styles import getSampleStyleSheet

doc_content = []
styles=getSampleStyleSheet()

doc = SimpleDocTemplate("form_letter.pdf",pagesize=letter,
                        rightMargin=72,leftMargin=72,
                        topMargin=72,bottomMargin=18)

titleFormat = '<font size="16" name="Helvetica" color="#FF8100"><b><i>%s</i></b></font>'

def generateDoc(docName):
    paraTitle = Paragraph(titleFormat % 'Title', styles["Normal"])
    doc_content.append(paraTitle)
    doc.build(doc_content)

generateDoc("temp.pdf")

But this gave me the error

AttributeError: module 'reportlab.lib.colors' has no attribute '#FF8100'

I also tried 0xFF8100 but it gives the same error :

AttributeError: module 'reportlab.lib.colors' has no attribute '0xFF8100'

When I use some named colors, like red, it works fine. How do I use hexadecimal color values?

Solution

If you need to use text of different colors in a PDF, it’s a good idea to create a custom style sheet.
You can pass the hexadecimal code value to def HexColor(val, htmlOnly=False, hasAlpha=False).

from reportlab.lib import colors
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate
from reportlab.platypus.para import Paragraph
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle

doc_content = []
styles = getSampleStyleSheet()

#creating custom stylesheet
styles.add(ParagraphStyle(name='Content',
                          fontFamily='Helvetica',
                          fontSize=8,
                          textColor=colors. HexColor("#FF8100")))

doc = SimpleDocTemplate("form_letter.pdf", pagesize=letter,
                        rightMargin=72, leftMargin=72,
                        topMargin=72, bottomMargin=18)

#using a sample text here
titleFormat = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."

def generateDoc(docName):
    paraTitle = Paragraph(titleFormat, styles["Content"])
    doc_content.append(paraTitle)
    doc.build(doc_content)

generateDoc("temp.pdf")

Related Problems and Solutions