简体   繁体   中英

How to change the font size of an python pptx object

I would like to change the font size of the title and of the body of my pptx-presentation. I tried to set it via title_shape.font = Pt(15) and body_shape.font = Pt(10) , which does not work.

Here is my code:

from pptx import Presentation, util, text
from pptx.util import Cm, Pt
import fnmatch
import os

import contentOf_pptx as contOfPres


# ..............
# Generate presentation
# ..............
prs = Presentation()
#blank_slide_layout = prs.slide_layouts[6] #blank layout, see slide layout in powerpoint
title_only = prs.slide_layouts[5] #title only, see slide layout in powerpoint 



# ..............
# set layout
# ..............
bullet_slide_layout = prs.slide_layouts[1]
slide = prs.slides.add_slide(bullet_slide_layout)
shapes = slide.shapes

title_shape = shapes.title
title_shape.font = Pt(15)

body_shape = shapes.placeholders[1]
body_shape.font = Pt(10)

# ..............
# set relevant text objects
# ..............
title_shape.text = 'Test Title'

tf = body_shape.text_frame
tf.text = 'Test SubText'


# ----------------------------------
# Store pptx
# ----------------------------------
prs.save('C:\\tests\\test_pptx_python.pptx')

A Shape object does not have a .font attribute (at least it didn't until you added one by assigning to that name :)

Font is characteristic of a Run object; a run is a sequence of characters that all share the same character formatting, also loosely known as a font .

A Paragraph object also has a .font property which is used the same way, but which specifies the default font for the runs in a paragraph. Individual runs in that paragraph can override that default by setting the attributes of their own font object.

If you only want one font for the shape (which is common), probably the fastest way is:

shape.text_frame.paragraphs[0].font.size = Pt(15)

which works because most shapes only contain a single paragraph (and all must contain at least one).

More thorough would be:

for paragraph in shape.text_frame.paragraphs:
    paragraph.font.size = Pt(15)

and more thorough still would be:

for paragraph in shape.text_frame.paragraphs:
    for run in paragraph.runs:
        run.font.size = Pt(15)

More details on this are in the documentation here:
https://python-pptx.readthedocs.io/en/latest/user/text.html

Here is a simple approach that worked for me:

slide = prs.slides.add_slide(blank_slide_layout)
slide.shapes.title.text = "The Title of My Slide"
slide.shapes.title.text_frame.paragraphs[0].font.size = Pt(15)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM