Text color by color hex values using `hex2dec` function

`pyFPDF` comes with an HTML module that helps turning HTML to PDF. One of its utility functions is `hex2dec()` which converts colors hex values to the RGB triplets we need for `set_text_color()`. The following code shows how to leverage that function.

# Import FPDF class
from fpdf import FPDF

# IMPORTANT: Import html module inside fpdf package and import hex2dec
from fpdf.html import hex2dec

# Create instance of FPDF class
# Letter size paper, use inches as unit of measure
pdf=FPDF(format='letter', unit='in')

# Add new page. Without this you cannot create the document.
pdf.add_page()

# Remember to always put one of these at least once.
pdf.set_font('Times','',10.0) 

# IMPORTANT: Notice the use of the operator '*' to unpack the triplet
pdf.set_text_color(*hex2dec('#8B6914'))
pdf.cell(0.5,0.0, u'Hello World!')
pdf.ln(0.15)

pdf.set_text_color(*hex2dec('#A020F0'))
pdf.cell(0.5,0.0, u'Hello World!')
pdf.ln(0.15)

pdf.set_text_color(*hex2dec('#FFA500'))
pdf.cell(0.5,0.0, u'Hello World!')
pdf.ln(0.15)

pdf.set_text_color(*hex2dec('#BFBFBF'))
pdf.cell(0.5,0.0, u'Hello World!')
pdf.ln(0.15)

pdf.output('colors-hex2dec.pdf','F')

colors-hex2dec

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s