Count number of lines of a powerpoint textbox

522 views Asked by At

I have been using python-pptx and if scanny sees this: Thank a lot for your work! It has been an absolute pleasure to work with this package. Every functionality I needed was some how available and if I couldn't find it, there was some answer on SO.

Can I count the number of lines my textbox uses after I have inserted my text? According to my reserach you can only count the paragraphs. Of course with some python wizardry I can calculate the amount words and characters but I guess I look for some functionality which in python-pptx might look like this len(text_frame.lines).

If that functionality is available it would be the icing of the cake! If somebody can do this functionality without using python-pttx or even python I am also interested.

Code snippet looks like this:

for slide in prs.slides: 
    for shape in slide.shapes: 
        text_frame = shape.text_frame
        key=[substring for substring in keys_dict if substring in text_frame.text]
        if 'My_Key' in key:
            text_frame.text=item_to_replace
            print(len(text_frame.paragraphs)) 
            # searched: len(text_frame.lines)
1

There are 1 answers

0
scanny On

The short answer is "No".

The reason why is that python-pptx is essentially a PowerPoint (.pptx) file editor and the number of rendered lines in a text box is not specified in the file. The .pptx file specifies the text, how it is divided into paragraphs and runs and the character formatting of each run, but the actual display characteristics, like which letter shows up in what location on the screen or printed page is all determined by the rendering engine.

In Microsoft PowerPoint, this is (part of) the PowerPoint application itself. Other clients like LibreOffice have their own rendering engines.

As you say, with some fancy programming you can approximate the values you mention, like how many lines it takes up and where the line-breaks occur, but in doing so you are implementing your own (partial) rendering engine. This of course cannot be guaranteed to always produce the same result as a particular client.

Note that not all clients will necessarily render identically. You wouldn't have to look far to find small differences in how a slide was rendered in Google Docs, for example, vs. PowerPoint.

Other related common questions like "How can I tell when my table is full so I can continue it on the next slide?" also cannot be solved without resorting to rendering.