Search code examples
pythonpython-pptx

python-pptx: read font color


I want to read the font color from a given textbox. I can extract font name and bold but not color (or font name).

Here's my code:

text_frame = shape.text_frame
paragraph = text_frame.paragraphs[0]

for run in paragraph.runs:
    font = run.font
    try:
        font_size = font.size.pt
        print(font_size)
        font_bold = font.bold
        print(font_bold)
        font_name = font.name
        print(font_name)
        color = font.color.rgb
        print(color)
    except:
        pass

returns:

36.0
True
None

thanks


Solution

  • In PowerPoint (roughly like CSS in this aspect), font attributes can be applied at a variety of levels in what's called (by some at least) the style hierarchy. The bottom level of these, that overrides any levels above, is applying the style directly to a particular run. Only a directly-applied attribute like this can be retrieved using the properties like .bold and .color.

    There could be attributes like .effective_bold and .effective_color which navigate the style hierarchy to calculate what value will be applied at rendering time, but there are not (yet).

    So the None value for font.color.rgb indicates that run inherits its color settings from its style hierarchy (e.g. paragraph default, shape default, theme, or presentation default, etc.) but unfortunately does not traverse the style hierarchy to determine what its effective color setting is.