Skip to content

Text Colors RGB to floats #2606

@pjaol

Description

@pjaol

Please mark as discussion and close, just providing it for anyone else who needs it
Might be useful to add to documentation as well

If you keep getting the following exception:

CheckColor
...
need 1, 3 or 4 color components in range 0 to 1

PyMuPDF uses float based RGB where (R/255, G/255, B/255)
This is a quick method to take hex color codes and convert them to rgb then float rgb

def hex_to_rgb(hex: str):
    if hex.startswith("#") :
        hex = hex[1:]
        
    return tuple(int(hex[i:i+2], 16) for i in (0, 2, 4))    


green = "#4ba36c"
rgb_green = hex_to_rgb(green) # returns a tuple of RGB (75, 163, 108)

# convert to float by dividing each value by 255

color_rgbf = tuple( list( map( lambda x: x/255, rgb_green )))



page = doc.load_page(0)
point = fitz.Point(650,40)
text = "hello moto"

page.insert_text(     
                                  point,  # bottom-left of 1st char
                                  text,  # the text (honors '\n')
                                  fontname = "helv",  # the default font
                                  fontsize = 17,  # the default font size
                                  rotate = 0,  # also available: 90, 180, 270
                                  color=color_rgbf,
                     )

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions