python-pptx icon indicating copy to clipboard operation
python-pptx copied to clipboard

python pptx get letter size

Open annaschi opened this issue 1 year ago • 7 comments

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?

annaschi avatar May 02 '23 09:05 annaschi

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 avatar May 02 '23 10:05 MartinPacker

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

MartinPacker avatar May 02 '23 10:05 MartinPacker

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...

annaschi avatar May 02 '23 12:05 annaschi

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.

MartinPacker avatar May 02 '23 13:05 MartinPacker

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.

annaschi avatar May 02 '23 13:05 annaschi

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.)

MartinPacker avatar May 03 '23 05:05 MartinPacker

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

sedrew avatar Jun 07 '23 06:06 sedrew