feat(text): add shrink_text_to_fit method for dynamic font resizing by BastienGimbert · Pull Request #1107 · scanny/python-pptx

Problem & Solution: Text Autofit in python-pptx

The Problem

When you set text_frame.auto_size = MSO_AUTO_SIZE.TEXT_TO_FIT_SHAPE in python-pptx, it only sets the XML flag (a:normAutofit). PowerPoint is supposed to recalculate the font size when opening the file, but it doesn't do it automatically - you have to manually open the file and activate/deactivate the functionality to trigger the resize.

The Solution

I added a new method shrink_text_to_fit() to the TextFrame class that:

  1. Calculates the optimal font size using the existing TextFitter class
  2. Applies that size immediately to all text (including defRPr)
  3. Sets the TEXT_TO_FIT_SHAPE flag so PowerPoint continues to auto-adjust if text is modified later

Usage

text_frame.shrink_text_to_fit(
    font_family="Calibri",
    max_size=24,      # Maximum font size
    min_size=6        # Minimum font size (fallback)
)

Files Modified

File Change
src/pptx/text/text.py Added shrink_text_to_fit() method
src/pptx/text/layout.py Fixed crash when text is too long to fit at any size

I also added an unit test to, that pass.