PowerPoint presentations are an essential tool for sharing ideas, data, and projects in a visual and engaging way. However, manually creating slides can be a time-consuming and repetitive process, especially when dealing with dynamically generated content, such as business reports or data analysis.
With Python, you can automate the creation of PowerPoint presentations, making the process more efficient and customizable. In this article, we will explore how to use the Python library python-pptx
to programmatically create and edit PowerPoint presentations.
We will see how to add text and tables to slides, all through simple Python scripts.
🔗 Do you like Techelopment? Check out the site for all the details!
Setup (Windows)
Let's start by installing the library that will allow us to create the PowerPoint file (from here on pptx). Open the terminal (Win+r
type cmd
and then Enter
) and launch the following command:
pip install python-pptx
At this point we are ready to open our favorite IDE and start writing our python code, so let's start by importing the library:
from pptx import Presentation
Creating the pptx file
Let's create a simple pptx to start getting familiar with the library and its functions.
from pptx import Presentation
print("\nCreation of pptx file....")
prs = Presentation()
title_subtitle_slide_layout = prs.slide_layouts[0]
slide = prs.slides.add_slide(title_subtitle_slide_layout)
print("End creation")
from datetime import datetime
file_name_pptx = 'my_pptx_' + datetime.today().strftime('%d%m%Y') + '.pptx'
print(f"\nSaving pptx file '{file_name_pptx}'...")
prs.save('C:\\Temp\\' + file_name_pptx)
print('Saving completed successfully')
input("\nHit Enter to exit...")
Let's see in detail the most important instructions:
- Thanks to
Presentation()
we create the object that represents our pptx - To create a slide we must first retrieve a
layout
and to do so we use a slide master. Through theslide_layouts
collection we access the first layout corresponding to the first Slide Master of the pptx (slide_layouts[0]
) and assign it to thetitle_subtitle_slide_layout
variable. A presentation can have more than one slide master and each master will have its own set of layouts. This property is a convenience for the most frequent cases in which the presentation has only a single slide master. - We can now add a slide thanks to the
add_slide
method by passing the layout of the first slide master as input. - Finally we save the pptx to a file by adding the current date (
datetime.today()
) to the end of the file name.
Let's add a text
To add a text we need to integrate the import part with the following instruction useful for defining the dimensions of our contents:
from pptx.util import Inches
We are now ready to add a simple Hello pptx text!
print("\nCreation of pptx file....")
prs = Presentation()
title_subtitle_slide_layout = prs.slide_layouts[0]
slide = prs.slides.add_slide(title_subtitle_slide_layout)
#get shapes to manage pptx contents
shapes = slide.shapes
#add text
left = top = Inches(1)
width = Inches(2)
height = Inches(1)
text_box = shapes.add_textbox(left, top, width, height)
#frame where to insert text
text_frame = text_box.text_frame
text_frame.text = "Hello pptx!"
print("End creation")
-
shapes
: whatever operation you want to do, for shapes you have to pass 😊. Shapes is the fundamental object to be able to interact with the contents of the slides - dimensions: we define height, width and positioning (left, top) of the box where I insert the text
-
text_box
: creation of a text box thanks to theadd_textbox
method -
text_frame
: finally thanks to thetext_frame
object we can add a text usingtext_frame.text
As you can see from the image, in our slide master there are already two text boxes for the title and subtitle. Let's see how to add text to these shapes already present in the slide:
print("\nCreation of pptx file....")
prs = Presentation()
title_subtitle_slide_layout = prs.slide_layouts[0]
slide = prs.slides.add_slide(title_subtitle_slide_layout)
#get shapes to manage pptx contents
shapes = slide.shapes
#add text
left = top = Inches(1)
width = Inches(2)
height = Inches(1)
text_box = shapes.add_textbox(left, top, width, height)
#frame where to insert text
text_frame = text_box.text_frame
text_frame.text = "Hello pptx!"
#modify Title and Subtitle inherited from Slide Master
title_box = shapes[0]
title_box.text = "My Title"
subtitle_box = shapes[1]
subtitle_box.text = "My Subtitle"
print("End creation")
Unfortunately the python-pptx
library does not allow removing elements (shapes
) so to create a completely empty slide you need to add an empty master slide to use as a layout
as shown below:
Save the file and, with the following 2 lines of code, we can add a blank slide to our pptx:
empty_layout = prs.slide_layouts[6] #index of new empty slide added in Slide Master
slide_empty = prs.slides.add_slide(empty_layout)
Let's add a table
To add a table we must first define the rows, columns and dimensions. With the shapes.add_table(…)
statement we add the table to the slide and with .table
we obtain the reference to be able to manipulate it:
from pptx import Presentation
from pptx.util import Inches
print("\nCreation of pptx file....")
prs = Presentation()
title_only_layout = prs.slide_layouts[5]
slide = prs.slides.add_slide(title_only_layout)
#get shapes to manage pptx contents
shapes = slide.shapes
#filling title of the slide
shapes.title.text="Follow Techelopment"
#table rows and columns
rows = 4
cols = 4
#table position and dimensions
left = Inches(0.8)
top = Inches(2.0)
width = Inches(8.0)
height = Inches(2.0)
#table creation
table = shapes.add_table(rows, cols, left, top, width, height).table
print("End creation")
from datetime import datetime
file_name_pptx = 'my_pptx_' + datetime.today().strftime('%d%m%Y') + '.pptx'
print(f"\nSaving pptx file '{file_name_pptx}'...")
prs.save('C:\\Temp\\' + file_name_pptx)
print('Saving completed successfully')
input("\nHit Enter to exit...")
Now let's start populating the table starting from the header containing the following entries:
- Header column 1: Social
- Header column 2: Instant Messaging
- Header column 3: Articles
- Header column 4: Video
To better manage the references to the cells in which we will insert the text, let's define constants that help us quickly identify the column indexes. Furthermore, these constants will make the code more understandable:
#define COLUMNS INDEX constants to easy manage the table cell filling
COLUMN_SOCIAL = 0
COLUMN_IM = 1
COLUMN_ARTICLES = 2
COLUMN_VIDEO = 3
# set column widths
table.columns[COLUMN_SOCIAL].width = Inches(1.7)
table.columns[COLUMN_IM].width = Inches(2.2)
table.columns[COLUMN_ARTICLES].width = Inches(2.3)
table.columns[COLUMN_VIDEO].width = Inches(1.8)
# write header
table.cell(0, COLUMN_SOCIAL).text = 'Social'
table.cell(0, COLUMN_IM).text = 'Instan Messaging'
table.cell(0, COLUMN_ARTICLES).text = 'Articles'
table.cell(0, COLUMN_VIDEO).text = 'Video'
Let's move on to the content of the table. We will add the following entries to the table corresponding to the relevant column:
- Social column:
- X (formerly Twitter)
- Instant Messaging column:
- Telegram
- Articles column:
- Medium (Italian)
- Dev.to (English)
- Video column:
- Youtube
#define content
social = ["Facebook", "Instagram", "X (ex twitter)"]
im = ["Telegram", "WhatsApp"]
articles = ["Medium (italian)", "Dev.to (english)"]
video = ["Youtube"]
#link the content with its column
column_content = {COLUMN_SOCIAL:social, COLUMN_IM:im, COLUMN_ARTICLES:articles, COLUMN_VIDEO:video}
# Iterate over column_content dict
for column, platforms in column_content.items():
i = 1 #because the row with index 0 belongs to the header
for platform in platforms:
# add content to the table
table.cell(i, column).text = platform
i += 1
Below is the complete script and the final result of the created pptx:
from pptx import Presentation
from pptx.util import Inches
print("\nCreation of pptx file....")
prs = Presentation()
title_only_layout = prs.slide_layouts[5]
slide = prs.slides.add_slide(title_only_layout)
#get shapes to manage pptx contents
shapes = slide.shapes
shapes.title.text="Follow Techelopment"
#table rows and columns
rows = 4
cols = 4
#table position and dimensions
left = Inches(0.8)
top = Inches(2.0)
width = Inches(8.0)
height = Inches(2.0)
#table creation
table = shapes.add_table(rows, cols, left, top, width, height).table
#define COLUMNS INDEX constants to easy manage the table cell filling
COLUMN_SOCIAL = 0
COLUMN_IM = 1
COLUMN_ARTICLES = 2
COLUMN_VIDEO = 3
# set column widths
table.columns[COLUMN_SOCIAL].width = Inches(1.7)
table.columns[COLUMN_IM].width = Inches(2.2)
table.columns[COLUMN_ARTICLES].width = Inches(2.3)
table.columns[COLUMN_VIDEO].width = Inches(1.8)
# write header
table.cell(0, COLUMN_SOCIAL).text = 'Social'
table.cell(0, COLUMN_IM).text = 'Instan Messaging'
table.cell(0, COLUMN_ARTICLES).text = 'Articles'
table.cell(0, COLUMN_VIDEO).text = 'Video'
#define content
social = ["Facebook", "Instagram", "X (ex twitter)"]
im = ["Telegram", "WhatsApp"]
articles = ["Medium (italian)", "Dev.to (english)"]
video = ["Youtube"]
#link the content with its column
column_content = {COLUMN_SOCIAL:social, COLUMN_IM:im, COLUMN_ARTICLES:articles, COLUMN_VIDEO:video}
# Iterate over column_content dict
for column, platforms in column_content.items():
i = 1 #index of row where insert the content. Start from 1 because the row with index 0 belongs to the header
for platform in platforms:
# add content to the table
table.cell(i, column).text = platform
i += 1
print("End creation")
from datetime import datetime
file_name_pptx = 'my_pptx_' + datetime.today().strftime('%d%m%Y') + '.pptx'
print(f"\nSaving pptx file '{file_name_pptx}'...")
prs.save('C:\\Temp\\' + file_name_pptx)
print('Saving completed successfully')
input("\nHit Enter to exit...")
That’s all but…
In this article, we explored how to automate the creation of PowerPoint presentations using Python and the python-pptx
library. From generating slides to managing custom layouts and content such as text and tables, we learned how the tools Python offers can speed up and streamline the slide creation process.
This guide lays the foundation for building custom automated solutions. The examples shown can be expanded and evolved based on the specific needs of each project, allowing you to create more complex scripts to manage dynamic layouts, integrate data from other sources, or create completely automated presentations with minimal manual intervention. With the right approach, Python can transform PowerPoint creation from a repetitive task to a fluid and customizable process.
Automating slide creation not only opens the door to greater creativity and flexibility in presenting content, but it saves valuable time as well.
Follow me #techelopment
Official site: www.techelopment.it
Medium: @techelopment
Dev.to: Techelopment
facebook: Techelopment
instagram: @techelopment
X: techelopment
telegram: @techelopment_channel
youtube: @techelopment
whatsapp: Techelopment
Top comments (1)
You made our life so much easier