scanny / python-pptx

Create Open XML PowerPoint documents in Python
MIT License
2.39k stars 518 forks source link

MSO_AUTO_SIZE.TEXT_TO_FIT_SHAPE attribute does not take effect #973

Open taige666 opened 4 months ago

taige666 commented 4 months ago

I am writing a script to extract the text content in pptx files and translate it into other languages. The problem I encountered is that when the translated text in the text box exceeds the length, this will cause the contents of adjacent text boxes to obscure each other. So I tried to set the MSO_AUTO_SIZE.TEXT_TO_FIT_SHAPE attribute to ensure that the text is automatically reduced when it overflows, but it did not work after running the code. The following is my code. Thank you very much for your advice.

    from pptx.enum.text import MSO_AUTO_SIZE

Loop through the shapes in each slide

for slide in prs.slides: for shape in slide.shapes: if not shape.has_text_frame: continue text_frame = shape.text_frame

Iterate through all paragraphs and running text

for paragraph in text_frame.paragraphs: for run in paragraph.runs:

Remove explicit font size setting

run.font.size = None

Set automatic text size adjustment

text_frame.auto_size = MSO_AUTO_SIZE.NONE text_frame.word_wrap = True text_frame.auto_size = MSO_AUTO_SIZE.TEXT_TO_FIT_SHAPE prs.save(path)

dirkesquire commented 4 months ago

I have the same problem. I wonder if python-pptx is really even able to calculate the correct size. The calculation seems to only happen when you open the Excel file, and slightly tweak the shape size, or the text. This is a big problem for exports, because nothing really ever fits onto the single slide properly.

MartinPacker commented 4 months ago

Calculating the correct size would require using font metrics - which I don't believe python-pptx has access to or understanding of.

dirkesquire commented 4 months ago

I just found this method which looks interesting:

shape.text_frame.fit_text()

It doesn't quite work for me because I'm running linux in a docker container which is an unsupported OS, but it might work for others.

It seems that python-pptx does have some understanding of fonts (although I'm unsure if font 'metrics' is a specific term). The following class looks interesting: pptx.text.fonts.py - especially the _best_fit_font_size method.

MartinPacker commented 4 months ago

If you want to know how long a certain character string is you need font metrics - which describe the width of pairs of neighbouring characters. The only exception to this is fixed-pitch fonts.