Python-pptx determine if text still within the slide

1.6k views Asked by At

I am using the Python library python-pptx to generate some powerpoint and in some case - the text that is being generating is outside the slide ( because there are two many bullet or the text is too big ).

For example :

+------------------------------------------+
|     Title of the slide                   |
+-------+-----------------------+----------|
|     o - First Bullet                     |
|     o - Second bullet                    |
|     o - Third bullet                     |
+------------------------------------------+ <-- End of slide 
      o - Fourth bullet    <- Out of slide
      o - Fifth  bullet    <- Out of slide

So I was wondering if there any utility to detect that the text is getting out of the place holder or out of the slide ?

Thanks in advance,

Florian

3

There are 3 answers

0
Steve Rindsberg On

If the python-pptx library has a way of accessing the BoundTop and BoundHeight properties of the text box, you can use that:

A VBA example you can test within PPT to get an idea how it works; be sure to select a text box before running it:

Sub InOrOut()
    Dim osh As Shape
    Set osh = ActiveWindow.Selection.ShapeRange(1)
    With osh.TextFrame.TextRange
        If .BoundTop + .BoundHeight > osh.Top + osh.Height Then
            MsgBox "Text is out of the box"
        End If
    End With
End Sub

You'll likely notice some slight variances with this; if you need to be more precise, you'll want to take the TextFrame's .MarginTop and .MarginBottom into account as well.

Test .BoundTop + .BoundHeight against ActivePresentation.PageSetup.SlideHeight to determine whether the text is off the bottom of the slide or not.

0
danieltellez On

You can use MSO_AUTO_SIZE.TEXT_TO_FIT_SHAPE like that:

from pptx.enum.text import MSO_AUTO_SIZE
...
content_ph = slide.placeholders[1]
content = body_content_ph.text_frame
content.clear()
content.auto_size = MSO_AUTO_SIZE.TEXT_TO_FIT_SHAPE

You can find more information regarding on autosize here: http://python-pptx.readthedocs.io/en/latest/api/enum/MsoAutoSize.html

0
Florian On

For what it worth ... I end up doing the work manually.

In my case a line can have 68 characters. So each the number of line required by a text would be :

number_of_line = text/68 + 1

In my case I would have 6 lines in my shape so I every-time I would add some text I would first ensure that number_of_line + text/68 + 1 <= 6. If it is false - then I would add a new slide.