run.font.italic and run.font.bold return None instead of True

Question:

I need to get all text that is italic and bold in paragraphs. I am manually turning text into italic and bold form but the code below returns none. Is it only an initiator or can we get the value out of it as well, how can I get all italic and bold text?

def get_italic_ratio(slide):
    count = 0
    for shape in slide.shapes:
        if not shape.has_text_frame:
            continue
        text_frame = shape.text_frame
        par = text_frame.paragraphs[0]
        run = par.add_run()
        print(run.font.italic) # returns None, should return True 
        print(run.font.bold) # returns None, should return True 

        print(text_frame.paragraphs)
Asked By: Rami.K

||

Answers:

I believe your question is how to find the “effective” value of a font formatting parameter.

The formatting for a run of text is determined by a set of rules operating on the style hierarchy. If a formatting attribute (say bold) is applied directly to the run, that takes precedence. When bold is not applied directly, run.bold returns None, and the run’s “boldness” is determined by checking the rest of the style hierarchy. This could be properties on the slide layout, the slide master or a theme or presentation default (and perhaps other possibilities).

So finding the effective value requires discovering these rules and navigating the style hierarchy to resolve them for any given piece of text. There is no API support in python-pptx for this yet.

Answered By: scanny

If the default font size, name, boldness, etc. was never changed then pptx returns None. You can change the attributes and then it should show the correct values.

Answered By: Philip
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.