How to access font size of text inside of text frame in pptx file by using python

61 Views Asked by At

Here is my code:

from pptx import Presentation

    pptx_file = 'education.pptx'
    presentation = Presentation(pptx_file)

    for slide_number, slide in enumerate(presentation.slides):
        # Iterate through each shape in the slide
        for shape in slide.shapes:
            if shape.has_text_frame:
                # Iterate through each paragraph in the text frame
                for paragraph in shape.text_frame.paragraphs:
                    # Iterate through each run in the paragraph
                    for run in paragraph.runs:
                        font_size = run.font.size
                        # font_size is in Pt, convert to a human-readable format if necessary
                        font_size_pt = font_size.pt if font_size else 'Default size'
                        print(f"Slide {slide_number + 1}, Text: {run.text}, Font size: {font_size_pt}")

I am trying to access font size of text inside of text frame in my pptx file by using python-pptx. Hovewer is keeping to repeate 'Default size'.

I tried did my best to get access font size of text frame. I have read documentation, but could find any valid answer for my question. I hope, anyone can help.

2

There are 2 best solutions below

7
Martin Packer On

In my (md2pptx) project I have the line:

if font.size < Pt(24):

which works for me.

It needs:

from pptx.util import Pt
1
Chathura Abeywickrama On

The issue may be due to accessing the font size at the run level, where it might not be explicitly set. Try accessing the font size at the paragraph level.

from pptx import Presentation

pptx_file = 'education.pptx'
presentation = Presentation(pptx_file)

for slide_number, slide in enumerate(presentation.slides):
    # Iterate through each shape in the slide
    for shape in slide.shapes:
        if shape.has_text_frame:
            # Iterate through each paragraph in the text frame
            for paragraph in shape.text_frame.paragraphs:
                font_size = paragraph.style.font.size
                # font_size is in Pt, convert to a human-readable format if necessary
                font_size_pt = font_size.pt if font_size else 'Default size'
                print(f"Slide {slide_number + 1}, Text: {paragraph.text}, Font size: {font_size_pt}")