Skip to main content
Practice

Changing Font, Size, and Color of Text

Have you ever tried making important text large and bold and highlighting portions you need to emphasize with eye-catching colors while working on a PPT?

To create slides with high readability, it's important to finely adjust the font, size, and color of the text.

In this lesson, we will learn how to format text using the python-pptx library.


Basic Structure for Formatting

Let's first look at the process of creating a text box within a slide and then adding text to it.

Formatting Text
# Add a text box (1 inch from the left, 1 inch from the top)
left = Inches(1)
top = Inches(1)

# Size of the text box (width 5 inches, height 1 inch)
width = Inches(5)
height = Inches(1)

# Add the text box
textbox = slide.shapes.add_textbox(left, top, width, height)

# Get the text frame
text_frame = textbox.text_frame

# Add text and format the first part of the text
text_frame.text = "Hello, World!"

# Add more text and format it
run = text_frame.paragraphs[0].add_run()

# Set the text value
run.text = "This is CodeFriends!"

# Set the font size
run.font.size = Pt(24)

# Set the font weight (bold)
run.font.bold = True

# Set the text color (red)
run.font.color.rgb = RGBColor(255, 0, 0)

Code Explanation

  • run = text_frame.paragraphs[0].add_run() : When formatting text, you use the run object. A run is a segment of text that can have its own formatting.

  • run.font.size = Pt(24) : Sets the size of the text to 24 points. Points (Pt) are units used to set font size, where 1 point is approximately 1/72 of an inch.

  • run.font.bold = True : Sets the text to bold. To set the text to bold, set this to True, and to remove bold formatting, set it to False.

  • run.font.color.rgb = RGBColor(255, 0, 0) : Sets the color of the text to red. Here, RGBColor(255, 0, 0) specifies the color using RGB (Red, Green, Blue) values, with each value being an integer between 0 and 255. In this example, the R (Red) value is 255, so RGBColor(255, 0, 0) represents the color red.


Additional Formatting Options

You can apply various formatting options, such as adding an underline to the text or setting it to a specific font.

  • run.font.italic = True : Sets the text to italic. To remove italic formatting, set this to False.

  • run.font.underline = True : Adds an underline to the text. To remove the underline, set this to False.

  • run.font.name = 'Arial' : Sets the font of the text to Arial. To change the font, specify the desired font name.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.