Adding Text Box and Text to Slides
Need to transfer a lot of data from an Excel file to a PowerPoint for your report?
How can you automate such repetitive tasks?
With python-pptx
, you can programmatically transfer large amounts of data to a PowerPoint file.
In this lesson, we will learn how to add a text box to a slide and insert text into it using Python.
Creating a Text Box to Write on a Slide
To input text on a slide, you first need to create a text box
to contain the text.
A text box provides a space on the slide where text can be written, specifying the position
and size
for the text.
While the position of a text box is typically specified in points (pt)
, you can also use units such as inches
, centimeters (cm)
, or EMUs
.
To specify or convert units, you can use classes like Inches
, Cm
, Pt
, and Emu
from the pptx.util
module.
For example, pptx.util.Inches(1)
represents 1 inch, and pptx.util.Cm(2)
represents 2 centimeters.
Adding a Text Box
You can add a text box to a desired location on your slide using the slide.shapes.add_textbox()
method from the python-pptx library.
Here is a simple example code to generate and place a text box on a slide.
from pptx import Presentation
# Convert length units using the Inches module
from pptx.util import Inches
# Create a Presentation object
prs = Presentation()
# Add a slide
slide = prs.slides.add_slide(prs.slide_layouts[5])
# Add a text box (1 inch from the left, 1 inch from the top)
left = Inches(1)
top = Inches(1)
# Text box size (5 inches wide, 1 inch high)
width = Inches(5)
height = Inches(1)
# Create the text box
textbox = slide.shapes.add_textbox(left, top, width, height)
# Get the text frame from the text box
text_frame = textbox.text_frame
# Add text
text_frame.text = "Hello, World!"
# Save the file
prs.save('output_file.pptx')
When you run the above code, a PowerPoint file named output_file.pptx
is created, with the slide containing the text "Hello, World!".
The text box is positioned 1 inch from the left and 1 inch from the top of the slide, with dimensions of 5 inches in width and 1 inch in height.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.