scanny / python-pptx

Create Open XML PowerPoint documents in Python
MIT License
2.28k stars 503 forks source link

python pptx get letter size #883

Open annaschi opened 1 year ago

annaschi commented 1 year ago

I have a presentaion. It contains a slide with an Text Frame. I import the presentaion and walk through the shapes of the slide. I want to get the lettersize of the text. How is that possible?

MartinPacker commented 1 year ago

That would be the size attribute of the font object for each run (of each paragraph). From the way I've written this you'll see there might be multiple font sizes. That doesn't negate what you're trying to do.

One shortcut might be - for the single font size case:

font_size = text_frame.paragraphs[0].font.size
MartinPacker commented 1 year ago

However, that's the font size, rather than the width of any piece of text. You can't get the latter.

annaschi commented 1 year ago

I want to replace a text in a text frame. This is a part of my code:

for string_to_replace in values: if string_to_replace in shape.text: text = shape.text text_neu = text.replace(string_to_replace, values[string_to_replace])

text_frame = shape.text_frame

text_frame.clear() p = text_frame.paragraphs[0] p.text = text_neu

It replaces the text correctly, but the size of the letters is different after the replacement.

I tried to get the size of the textframe and put it on the textframe after replacement. If I try to read with font.size it gives me None back...

MartinPacker commented 1 year ago

My GUESS is it's the text_frame.clear() that's resetting to the default for this slide master. And that that is different from what the original paragraphs' runs were using.

annaschi commented 1 year ago

Do you have a suggestion for my problem?

I have a presentation that contains a slide with a textframe. The text is: "Tested variable_variant".

The target is to get the text of the shape. And then put in a string for the variable "variable_variant". The position of the shape and the size of the text should be the same.

MartinPacker commented 1 year ago

Is the term you are replacing always contained within a single run? If not you're going to break whatever (perhaps invisible) formatting variations.

(The general "search and replace" question comes up quite often, especially using the python-pptx tag on Stack Overflow. In fact this question might get better discussion there.)

sedrew commented 1 year ago

Try it. https://github.com/scanny/python-pptx/issues/884#issuecomment-1578676563

Or

def set_font(run: _Run, font: Font) -> _Run:
    run._r.insert(0, font._rPr)
    return run