- Python Basics
- Interview Questions
- Python Quiz
- Popular Packages
- Python Projects
- Practice Python
- AI With Python
- Learn Python3
- Python Automation
- Python Web Dev
- DSA with Python
- Python OOPs
- Dictionaries
Creating and updating PowerPoint Presentations in Python using python – pptx
python-pptx is library used to create/edit a PowerPoint (.pptx) files. This won’t work on MS office 2003 and previous versions. We can add shapes, paragraphs, texts and slides and much more thing using this library.
Installation: Open the command prompt on your system and write given below command:
Let’s see some of its usage:
Example 1: Creating new PowerPoint file with title and subtitle slide.
Example 2: Adding Text-Box in PowerPoint.
Example 3: PowerPoint (.pptx) file to Text (.txt) file conversion.
Example 4: Inserting image into the PowerPoint file.
Example 5: Adding Charts to the PowerPoint file.
Example 6: Adding tables to the PowerPoint file.
Please Login to comment...
Similar reads.
- python-modules
- python-utility
Improve your Coding Skills with Practice
What kind of Experience do you want to share?
- Mailing List
Practical Business Python
Taking care of business, one python script at a time
Creating Powerpoint Presentations with Python
Posted by Chris Moffitt in articles
Introduction
Love it or loathe it, PowerPoint is widely used in most business settings. This article will not debate the merits of PowerPoint but will show you how to use python to remove some of the drudgery of PowerPoint by automating the creation of PowerPoint slides using python.
Fortunately for us, there is an excellent python library for creating and updating PowerPoint files: python-pptx . The API is very well documented so it is pretty easy to use. The only tricky part is understanding the PowerPoint document structure including the various master layouts and elements. Once you understand the basics, it is relatively simple to automate the creation of your own PowerPoint slides. This article will walk through an example of reading in and analyzing some Excel data with pandas, creating tables and building a graph that can be embedded in a PowerPoint file.
PowerPoint File Basics
Python-pptx can create blank PowerPoint files but most people are going to prefer working with a predefined template that you can customize with your own content. Python-pptx’s API supports this process quite simply as long as you know a few things about your template.
Before diving into some code samples, there are two key components you need to understand: Slide Layouts and Placeholders . In the images below you can see an example of two different layouts as well as the template’s placeholders where you can populate your content.
In the image below, you can see that we are using Layout 0 and there is one placeholder on the slide at index 1.
In this image, we use Layout 1 for a completely different look.
In order to make your life easier with your own templates, I created a simple standalone script that takes a template and marks it up with the various elements.
I won’t explain all the code line by line but you can see analyze_ppt.py on github. Here is the function that does the bulk of the work:
The basic flow of this function is to loop through and create an example of every layout included in the source PowerPoint file. Then on each slide, it will populate the title (if it exists). Finally, it will iterate through all of the placeholders included in the template and show the index of the placeholder as well as the type.
If you want to try it yourself:
Refer to the input and output files to see what you get.
Creating your own PowerPoint
For the dataset and analysis, I will be replicating the analysis in Generating Excel Reports from a Pandas Pivot Table . The article explains the pandas data manipulation in more detail so it will be helpful to make sure you are comfortable with it before going too much deeper into the code.
Let’s get things started with the inputs and basic shell of the program:
After we create our command line args, we read the source Excel file into a pandas DataFrame. Next, we use that DataFrame as an input to create the Pivot_table summary of the data:
Consult the Generating Excel Reports from a Pandas Pivot Table if this does not make sense to you.
The next piece of the analysis is creating a simple bar chart of sales performance by account:
Here is a scaled down version of the image:
We have a chart and a pivot table completed. Now we are going to embed that information into a new PowerPoint file based on a given PowerPoint template file.
Before I go any farther, there are a couple of things to note. You need to know what layout you would like to use as well as where you want to populate your content. In looking at the output of analyze_ppt.py we know that the title slide is layout 0 and that it has a title attribute and a subtitle at placeholder 1.
Here is the start of the function that we use to create our output PowerPoint:
This code creates a new presentation based on our input file, adds a single slide and populates the title and subtitle on the slide. It looks like this:
Pretty cool huh?
The next step is to embed our picture into a slide.
From our previous analysis, we know that the graph slide we want to use is layout index 8, so we create a new slide, add a title then add a picture into placeholder 1. The final step adds a subtitle at placeholder 2.
Here is our masterpiece:
For the final portion of the presentation, we will create a table for each manager with their sales performance.
Here is an image of what we’re going to achieve:
Creating tables in PowerPoint is a good news / bad news story. The good news is that there is an API to create one. The bad news is that you can’t easily convert a pandas DataFrame to a table using the built in API . However, we are very fortunate that someone has already done all the hard work for us and created PandasToPowerPoint .
This excellent piece of code takes a DataFrame and converts it to a PowerPoint compatible table. I have taken the liberty of including a portion of it in my script. The original has more functionality that I am not using so I encourage you to check out the repo and use it in your own code.
The code takes each manager out of the pivot table and builds a simple DataFrame that contains the summary data. Then uses the df_to_table to convert the DataFrame into a PowerPoint compatible table.
If you want to run this on your own, the full code would look something like this:
All of the relevant files are available in the github repository .
One of the things I really enjoy about using python to solve real world business problems is that I am frequently pleasantly surprised at the rich ecosystem of very well thought out python tools already available to help with my problems. In this specific case, PowerPoint is rarely a joy to use but it is a necessity in many environments.
After reading this article, you should know that there is some hope for you next time you are asked to create a bunch of reports in PowerPoint. Keep this article in mind and see if you can find a way to automate away some of the tedium!
- ← Best Practices for Managing Your Code Library
- Adding a Simple GUI to Your Pandas Script →
Subscribe to the mailing list
Submit a topic.
- Suggest a topic for a post
- Pandas Pivot Table Explained
- Common Excel Tasks Demonstrated in Pandas
- Overview of Python Visualization Tools
- Guide to Encoding Categorical Values in Python
- Overview of Pandas Data Types
Article Roadmap
We are a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for us to earn fees by linking to Amazon.com and affiliated sites.
- Open Source
How To Create PowerPoint Presentations With Python From Command Line
Automating the process of creating simple powerpoint slides with python-pptx library..
This Step-by-Step guide demonstrates how to use Python and the python-pptx library to create PowerPoint presentations from command line.
The steps and code provided in this guide are not specific to any particular operating system and should work on all major platforms, including Linux, macOS, and Windows.
Table of Contents
What is Python-pptx, by the way?
The python-pptx library is an open-source Python library that allows you to create, read, and update PowerPoint (.pptx) files.
The python-pptx library is particularly well-suited for generating PowerPoint presentations dynamically from various data sources as listed below:
- Database Queries : By connecting to a database and executing queries, you can fetch data and use the python-pptx library to generate PowerPoint slides with visualizations, charts, or tables based on the queried data. This approach can be useful for creating data-driven presentations or reports.
- Analytics Outputs : If you have analytics software or scripts that generate structured data or insights, you can use the python-pptx library to transform that data into visually appealing PowerPoint slides, complete with charts, graphs, and other visual elements.
- JSON Payloads : With the increasing prevalence of APIs and web services, it's common to receive data in JSON format. The python-pptx library can be used to parse JSON payloads and dynamically create PowerPoint slides based on the structured data contained within them.
- HTTP Requests : By integrating the python-pptx library into a web application or API, you can generate PowerPoint presentations on-the-fly in response to HTTP requests. This allows for the creation of dynamic, customized presentations tailored to specific user inputs or data sources.
The python-pptx library runs on any Python-capable platform, including Linux, macOS, and Windows.
Another significant benefit of the python-pptx library is that it does not require the PowerPoint application to be installed on the system where the code is running.
Now let us discuss how to automate the process of creating simple PowerPoint presentations using python-pptx library .
Create PowerPoint Presentations using Python
The process is divided into three straightforward steps: installing the required software, creating the Python script, and running the script to produce the presentation file.
Step 1 - Installing Prerequisites
Before proceeding, ensure that you have Python installed on your system.
Python is pre-installed in most Linux operating systems. If not, you can install it using the following command on Debian-based systems:
On Red-hat based systems, run:
Next, install the python-pptx library, which provides the necessary functionality to create PowerPoint presentations programmatically. You can install it using pip , Python's package installer:
Step 2 - Creating the Python Script
Create a new Python script (e.g., create_ppt.py ):
and copy the following code into it:
Edit the script and update the title, content of the slides and the output file as you wish. Once done, save the file and close it.
Explanation of the Script:
This script creates a new PowerPoint presentation and adds four slides: a title slide , and three content slides covering the importance of Linux security , common security practices , and security tools .
Title Slide :
The script initializes a new Presentation object and adds a title slide with the main title "Linux Security Automation" and the subtitle "An overview of securing Linux systems".
Content Slides :
The script then adds three content slides, each with a title and bullet points covering different aspects of Linux security:
- Slide 1: Importance of Linux Security (e.g., protecting against unauthorized access, ensuring data integrity, maintaining system availability, and protecting sensitive information).
- Slide 2: Common Security Practices (e.g., regularly updating and patching the system, using strong passwords, enabling firewalls, using antivirus software, and monitoring system logs).
- Slide 3: Security Tools (e.g., SELinux/AppArmor for Mandatory Access Control, ClamAV for antivirus protection, Fail2Ban for preventing brute force attacks, and UFW for an uncomplicated firewall).
Saving the Presentation :
Finally, the script saves the PowerPoint presentation as Linux_Security_Presentation.pptx in the current directory.
Step 3 - Generate PowerPoint Slides
Navigate to the directory containing the script in your terminal and run the following command:
This command will execute the script, and generate a new PowerPoint file named " Linux_Security_Presentation.pptx " in the same directory.
Step 4 - Run or Customize PPTs
As I mentioned, this script will only create simple PowerPoint presentations . They are plain with white background.
Here is a sample PPT slide that I created using this script:
You can open it with any PowerPoint application (For example LibreOffice Impress or MS PowerPoint ) and customize the look of the slides as per your own liking.
Here's how the slide looks like after I changed its background and added our blog's logo on the top of the slide:
This script serves as a basic example, and you can further enhance it by adding more slides, customizing the content, or incorporating additional features, such as adding images, charts, or formatting options.
You get the idea. Use our script as a starting point. Customize it and be creative. You can make the slides more elegant and professional.
- https://pypi.org/project/python-pptx/
Senthilkumar Palani (aka SK) is the Founder and Editor in chief of OSTechNix. He is a Linux/Unix enthusiast and FOSS supporter. He lives in Tamilnadu, India.
Alpine Linux 3.20.0 Released With Initial 64-bit RISC-V Support
Tuxedo stellaris slim 15 is available for pre-order, you may also like, pipenv – the officially recommended python packaging tool, get started with anaconda navigator graphical interface, how to manage python packages using pip in..., retrieve latest mirror list using reflector in arch..., how to install anaconda on linux, wisdom tree – a focus and productivity app..., leave a comment cancel reply.
Save my name, email, and website in this browser for the next time I comment.
This site uses Akismet to reduce spam. Learn how your comment data is processed .
This website uses cookies to improve your experience. By using this site, we will assume that you're OK with it. Accept Read More
Create interactive slides with Python in 8 Jupyter Notebook cells
Creating presentations in Jupyter Notebook is a great alternative to manually updating slides in other presentation creation software. If your data changes, you just re-execute the cell and slide chart is updated.
Jupyter Notebook is using Reveal.js (opens in a new tab) for creating slides from cells. The standard approach is to write slides code and Markdown in the Jupyter Notebook. When notebook is ready, it can be exported to standalone HTML file with presentation.
What if, you would like to update slides during the slide show? What is more, it would be fantastic to have interactive widgets in the presentation. You can do this in Mercury framework.
In this tutorial, we will create an interactive presentation in Jupyter Notebook and serve it with Mercury.
Create presentation in notebook
Please enable Slideshow toolbar in Jupyter Notebook. It can be done by clicking View -> Cell Toolbar -> Slideshow . It is presented in the screenshot below:
We will need following packages to create presentation in Python notebook:
Please make sure that they are installed in your environment.
1. Import packages and App setup
The first step is to import packages and setup Mercury App :
We setup title and description for App object.
Please note that we set Slide Type to Skip . This cell will not appear in the presentation.
2. Add title
The second cell is a Markdown with title:
The Slide Type is set to Slide . It is our first slide!
3. Add slide with Markdown
Add new Markdown cell with the following cell.
Please set Slide Type to Slide . It will be a second slide. I'm using ## as slide title ( # will produce too large title in my opinion).
4. Add Mercury Widget
Please add code cell with Text widget. We will use it, to ask users about their name.
We set Slide Type as Skip , so this cell will not appear in the presentation.
5. Display name
Let's use the name.value in the slide. Please add a code cell. We will display a Markdown text with Python variables by using Markdown function from Mercury package.
Please set the Slide Type to Slide .
You can display Markdown with Python variables by calling mr.Markdown() or mr.Md() functions. Both do the same.
The first five cells of the notebook:
You can enter your name in the widget during the notebook development. There will be no change in other cells. If you want to update the cell with new widget value, please execute it manually.
6. More widgets
We can add more widgets to the presentation. They will be used to control chart in the next slide.
We have used Slider and Select widgets. They are displayed in the notebook. This cell will not be displayed in the presentation, so set Slide Type to Skip .
7. Scatter plot
We will add a new code cell. It will have Slide Type set to Slide .
We used widgets values by accessing them with samples.value and color.value .
Screenshot of the notebook with scatter plot:
8. Final slide
Please add a last Markdown cell. Its Slide Type will be set to Slide :
Please notice that link is added with HTML syntax. There is a target="_blank" used to open link in a new tab.
Run presentation in Mercury
Please run Mercury local server in the same directory as notebook:
The above command will open a web browser at http://127.0.0.1:8000 . Please click on a card with presentation.
You can navigate between slides with arrows in the bottom right corner. You can enter the full screen mode by pressing F on the keyboard. Please use Esc to exit full screen mode.
You can change widgets values in the sidebar and presentation slides will be automatically recomputed:
You can export your slides as PDF or HTML by clicking Download button in the sidebar.
- python-pptx 1.0.0 documentation »
Working with Presentations ¶
python-pptx allows you to create new presentations as well as make changes to existing ones. Actually, it only lets you make changes to existing presentations; it’s just that if you start with a presentation that doesn’t have any slides, it feels at first like you’re creating one from scratch.
However, a lot of how a presentation looks is determined by the parts that are left when you delete all the slides, specifically the theme, the slide master, and the slide layouts that derive from the master. Let’s walk through it a step at a time using examples, starting with the two things you can do with a presentation, open it and save it.
Opening a presentation ¶
The simplest way to get started is to open a new presentation without specifying a file to open:
This creates a new presentation from the built-in default template and saves it unchanged to a file named ‘test.pptx’. A couple things to note:
- The so-called “default template” is actually just a PowerPoint file that doesn’t have any slides in it, stored with the installed python-pptx package. It’s the same as what you would get if you created a new presentation from a fresh PowerPoint install, a 4x3 aspect ratio presentation based on the “White” template. Well, except it won’t contain any slides. PowerPoint always adds a blank first slide by default.
- You don’t need to do anything to it before you save it. If you want to see exactly what that template contains, just look in the ‘test.pptx’ file this creates.
- We’ve called it a template , but in fact it’s just a regular PowerPoint file with all the slides removed. Actual PowerPoint template files (.potx files) are something a bit different. More on those later maybe, but you won’t need them to work with python-pptx .
REALLY opening a presentation ¶
Okay, so if you want any control at all to speak of over the final presentation, or if you want to change an existing presentation, you need to open one with a filename:
Things to note:
- You can open any PowerPoint 2007 or later file this way (.ppt files from PowerPoint 2003 and earlier won’t work). While you might not be able to manipulate all the contents yet, whatever is already in there will load and save just fine. The feature set is still being built out, so you can’t add or change things like Notes Pages yet, but if the presentation has them python-pptx is polite enough to leave them alone and smart enough to save them without actually understanding what they are.
- If you use the same filename to open and save the file, python-pptx will obediently overwrite the original file without a peep. You’ll want to make sure that’s what you intend.
Opening a ‘file-like’ presentation ¶
python-pptx can open a presentation from a so-called file-like object. It can also save to a file-like object. This can be handy when you want to get the source or target presentation over a network connection or from a database and don’t want to (or aren’t allowed to) fuss with interacting with the file system. In practice this means you can pass an open file or StringIO/BytesIO stream object to open or save a presentation like so:
Okay, so you’ve got a presentation open and are pretty sure you can save it somewhere later. Next step is to get a slide in there …
Table of Contents
- REALLY opening a presentation
- Opening a ‘file-like’ presentation
Previous topic
Getting Started
Working with Slides
Useful Links
- python-pptx @ GitHub
- python-pptx @ PyPI
- Issue Tracker
Quick search
Creating Presentations with Jupyter Notebook
Jupyter Notebook can be turned into a slide presentation that is kind of like using Microsoft Powerpoint, except that you can run the slide’s code live! It’s really neat how well it works. The only con in my book is that there isn’t a lot of theming that can be applied to your slides, so they do end up looking a bit plain.
In this article, we will look at two methods of creating a slideshow out of your Jupyter Notebook. The first method is by using Jupyter Notebook’s built-in slideshow capabilities. The second is by using a plug-in called RISE .
Let’s get started!
Note: This article assumes that you already have Jupyter Notebook installed. If you don’t, then you might want to go to their website and learn how to do so.
The first thing we need to do is to create a new Notebook. Once you have that done and running, let’s create three cells so that we can have three slides. Your Notebook should now look like the following:
Now let’s turn on the “slideshow” tools. Go to the View menu and then click on the Cell Toolbar menu option. You will find a sub-menu in there that is called Slideshow . Choose that. Now your Notebook’s cell should look like this:
There are now little comboboxes on the top right of each cell. These widgets give you the following options:
You can just create a series of Slides if you like, but you can make the slideshow a bit more interesting by adding Sub-Slides and Fragments. Sub-slides are just slides that are below the previous one while Fragments are basically fragments within the previous slide. As an aside, I have actually never used Fragments myself. Anyway you can also set a slide to Skip, which just allows you to skip a slide or Notes, which are just speaker notes.
Let’s add some text to our first cell. We will add the text “# Hello Slideshow” to it and set the cell type to Markdown. Note the pound sign at the beginning of the text. This will cause the text to be a heading.
In cell two, we can add a simple function. Let’s use the following code:
For the last cell, we will add the following text:
Make sure you set that to be a Markdown cell as well. This is what my cells ended up looking like when I was done:
To make things simple, just set each of the cell’s individual comboboxes to Slide .
Now we just need to turn it into an actual slideshow. To do that, you will need save your Notebook and shut down the Jupyter Notebook server. Next you will need to run the following command:
To navigate your slideshow, you can use your left and right arrow keys or you can use spacebar to go forward and shift_spacebar to go back. This creates a pretty nice and simple slideshow, but it doesn’t allow you to run the cells. For that, we will need to use the RISE plugin!
Getting Started with RISE
Reveal.js – Jupyter/IPython Slideshow Extension (RISE) is a plugin that uses *reveal.js* to make the slideshow run live. What that means is that you will now be able to run your code in the slideshow without exiting the slideshow. The first item that we need to learn about is how to get RISE installed.
Installing rise with conda
If you happen to be an Anaconda user, then this is the method you would use to install RISE:
This is the easiest method of installing RISE. However most people still use regular CPython, so next we will learn how to use pip!
Installing rise with pip
You can use Python’s pip installer tool to install RISE like this:
You can also do `python -m pip install RISE` is you want to. Once the package is installed, you have a second step of installing the JS and CSS in the proper places, which requires you to run the following command:
If you somehow get a version of RISE that is older than 5.3.0, then you would also need to enable the RISE extension in Jupyter. However, I recommend just using the latest version so you don’t have to worry about that.
Using RISE for a SlideShow
Now that we have RISE installed and enabled, let’s re-open the Jupyter Notebook we created earlier. Your Notebook should now look like this:
You will notice that I circled a new button that was added by RISE to your Notebook. If you mouse over that button you will see that it has a tooltip that appears that says “Enter/Exit RISE Slideshow”. Click it and you should see a slideshow that looks a lot like the previous one. The difference here is that you can actually edit and run all the cells while in the slideshow. Just double-click on the first slide and you should see it transform to the following:
After you are done editing, press SHIFT+ENTER to run the cell. Here are the primary shortcuts you will need to run the slideshow effectively:
- SPACEBAR – Goes forward a slide in the slideshow
- SHIFT+SPACEBAR – Goes back a slide in the slideshow
- SHIFT+ENTER – Runs the cell on the current slide
- DOUBLE-CLICK – To edit a Markdown cell
You can view all the Keyboard shortcuts by going to the Help menu when not in Slideshow mode and clicking the Keyboard Shortcuts option. Most if not all of these shortcuts should work inside of a RISE slideshow.
If you want to start the slideshow on a specific cell, just select that cell and then press the Enter Slideshow button.
RISE also works with Notebook widgets. Try creating a new cell with the following code:
Now start the slideshow on that cell and try running the cell (SHIFT+ENTER). You should see something like this:
You can use RISE to add neat widgets, graphs and other interactive elements to your slideshow that you can edit live to demonstrate concepts to your attendees. It’s really quite fun and I have used RISE personally for presenting intermediate level material in Python to engineers.
RISE also has several different themes that you can apply as will as minimal support for slide transitions. See the documentation for full information.
Wrapping Up
In this chapter we learned about two good methods for creating presentations out of our Jupyter Notebooks. You can use Jupyter directly via their nbconvert tooling to generate a slideshow from the cells in your Notebook. This is nice to have, but I personally like RISE better. It makes the presentations so much more interactive and fun. I highly recommend it. You will find that using Jupyter Notebook for your presentations will make the slides that much more engaging and it is so nice to be able to fix slides during the presentation too!
Related Reading
- Presenting code using Jupyter Notebook
- The RISE Github page
- Jupyter nbconvert Usage
- How to build interactive presentations with Jupyter Notebook and Reveal JS
4 thoughts on “Creating Presentations with Jupyter Notebook”
Pingback: Jupyter Notebook Extension Basics | The Mouse Vs. The Python
Pingback: Creating Jupyter Notebook Widgets with interact - The Mouse Vs. The Python
Pingback: How to Export Jupyter Notebooks into Other Formats - The Mouse Vs. The Python
Pingback: Jupyter Notebook Extension Basics - The Mouse Vs. The Python
Comments are closed.
5 Best Ways to Create PowerPoint Files Using Python
💡 Problem Formulation: Automating the creation of PowerPoint presentations is a common task for those who need to generate reports or summaries regularly. For instance, a user may wish to create a presentation summarizing sales data from a CSV file or visualize a project’s progress in a structured format. The desired output is a fully formatted PowerPoint file (.pptx) with various elements like titles, texts, images, and charts, as specified by the input data or customization requirements.
Method 1: Using python-pptx
The python-pptx library provides a comprehensive set of features for creating PowerPoint files (.pptx) in Python. It allows for adding slides, text, images, charts, and more, with a high level of customization. Manipulate slides at a granular level by accessing placeholders, creating bulleted lists, and setting properties like font size or color programmatically.
Here’s an example:
The code snippet above creates a PowerPoint file named python-pptx-presentation.pptx with one slide that includes a title and a subtitle.
In this overview, we create a presentation object, add a new slide with a predefined layout, set text for the title and subtitle placeholders, and then save the presentation. This method gives users the ability to create detailed, professional presentations through code.
Method 2: Using Pandas with python-pptx
This method combines the data manipulation power of Pandas with the presentation capabilities of python-pptx to create PowerPoint files from DataFrame contents. It’s particularly useful for automating the inclusion of tabular data or creating charts based on the DataFrame’s data.
The output is a PowerPoint file named pandas-python-pptx.pptx containing a bar chart representing the quantity of fruits.
This snippet demonstrates using a Pandas DataFrame to generate chart data, which is then used to create a chart in a PowerPoint slide. It showcases the synergy between Pandas for data handling and python-pptx for presentation creation.
Method 3: Using ReportLab with python-pptx
Those seeking to include complex graphics or generate custom visuals can harness the graphic-drawing capabilities of ReportLab with python-pptx. This method leverages ReportLab to create an image, which can then be inserted into a PowerPoint slide.
The output would be a PowerPoint file named reportlab-pptx.pptx containing a slide with a custom bar chart image.
The code above creates a bar chart using ReportLab, saves the chart as an image, and then inserts the image into a PowerPoint slide. This approach is ideal if you need to include bespoke graphics that are not directly supported by python-pptx itself.
Method 4: Using Matplotlib with python-pptx
For those familiar with Matplotlib, this method involves creating a visual plot or chart with Matplotlib, saving it as an image, and then embedding the image into a PowerPoint slide using python-pptx.
The outcome is a PowerPoint file matplotlib-pptx.pptx , with a plot on a slide created by Matplotlib.
In this case, we graph a quadratic function using Matplotlib, save it as an image, and then add that image to a slide in our PowerPoint presentation. This method offers a blend of Matplotlib’s sophisticated plotting tools with the simplicity of python-pptx.
Bonus One-Liner Method 5: Using Officegen
The Officegen package allows for rapid PowerPoint creation with simpler syntax, although with less flexibility compared to python-pptx. It provides functions to add slides, titles, and bullet points.
The outcome is a PowerPoint file officegen-presentation.pptx with a single slide containing a large title.
This snippet uses Officegen to initiate a new presentation, adds a text title to a slide, and saves the presentation. While not as detailed as python-pptx, Officegen is quick for simple presentations.
Summary/Discussion
- Method 1: python-pptx. Full-featured control over presentations. Can be verbose for simple tasks.
- Method 2: Pandas with python-pptx. Ideal for data-driven presentations. Setup can be complex if unfamiliar with data libraries.
- Method 3: ReportLab with python-pptx. Powerful combo for custom graphics. Requires separate handling of graphics and presentation stages.
- Method 4: Matplotlib with python-pptx. Best for users comfortable with Matplotlib. Less direct than using python-pptx alone.
- Bonus Method 5: Officegen. Quick and easy for simple presentations. Limited customization options.
- Trending Categories
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
How to create powerpoint files using Python
Introduction.
We’ve all had to make PowerPoint presentations at some point in our lives. Most often we’ve used Microsoft’s PowerPoint or Google Slides.
But what if you don’t have membership or access to the internet? Or what if you just wanted to do it the “programmers” way?
Well, worry not for Python’s got your back!
In this article you’ll learn how to create a PowerPoint file and add some content to it with the help of Python. So let’s get started!
Getting Started
Throughout this walkthrough, we’ll be using the python-pptx package. This package supports different python versions ranging from 2.6 to 3.6.
So, make sure you have the right version of Python installed on your computer first.
Next, open your terminal and type −
Once the module is successfully installed, you are all set to start coding!
Importing the Modules
Before we get into the main aspects of it, we must first import the right modules to utilise the various features of the package.
So, let’s import the presentation class that contains all the required methods to create a PowerPoint.
Now, we are all set to create a presentation.
Creating a Presentation
Let us now create an object of the Presentation class to access its various methods.
Next, we need to select a layout for the presentation.
As you can see, there are nine different layouts. In the pptx module, each layout is numbered from 0 to 8. So, “Title Slide” is 0 and the “Picture with Caption” is 8.
So, let us first add a title slide.
Now, we have created a layout and added a slide to our presentation.
Let us now add some content to the first slide.
In the above lines, we first add a title to the “first slide” and a subtitle using the placeholder.
Now, let us save the presentation. We can do this using the save command.
If you run the program, it will save the PowerPoint presentation in the directory where your program is saved.
You have successfully created your PowerPoint presentation.
Creating a second slide and adding some content
Firstly, you’ll need to import additional methods to add content.
Let us first create and add the second slide.
Adding title for the next slide,
Now, we must create a textbox and move its layout to suit our needs.
Let us position it and adjust its margins in inches.
The above line of code will place a textbox 3 Inches from left and 1.5 Inches from the top with a width of 3 Inches and height of 1 Inch.
Once we have the layout and position fixed, time to create a textframe to add content to.
Now to add a paragraph of content,
Finally, save the presentation again using the save method.
That’s it! You can now create your own presentation with the help of Python.
And there are a lot more features within the pptx package that allows you to completely customise your presentation from A-Z just the way you do it in GUI.
You can add images, build charts, display statistics and a lot more.
You can go through python-pptx official documentation for more syntaxes and features.
- Related Articles
- How to convert PDF files to Excel files using Python?
- How to remove swap files using Python?
- How to Create a list of files, folders, and subfolders in Excel using Python?
- How to rename multiple files recursively using Python?
- How to add audio files using Python kivy
- Tips for Using PowerPoint Presentation More Efficiently
- How to read text files using LINECACHE in Python
- How to touch all the files recursively using Python?
- How to ignore hidden files using os.listdir() in Python?
- How to remove hidden files and folders using Python?
- How to close all the opened files using Python?
- PowerPoint Alternatives
- How to copy files to a new directory using Python?
- How are files added to a tar file using Python?
- How are files added to a zip file using Python?
Kickstart Your Career
Get certified by completing the course
You are using an outdated browser. Please upgrade your browser to improve your experience.
Presentations Tool in Python/v3
How to create and publish a spectacle-presentation with the Python API.
New to Plotly? ¶
Plotly's Python library is free and open source! Get started by downloading the client and reading the primer . You can set up Plotly to work in online or offline mode, or in jupyter notebooks . We also have a quick-reference cheatsheet (new!) to help you get started!
Version Check ¶
Note: The presentations API is available in version 2.2.1.+ Run pip install plotly --upgrade to update your Plotly version.
Plotly Presentations ¶
To use Plotly's Presentations API you will write your presentation code in a string of markdown and then pass that through the Presentations API function pres.Presentation() . This creates a JSON version of your presentation. To upload the presentation online pass it through py.presentation_ops.upload() .
In your string, use --- on a single line to seperate two slides. To put a title in your slide, put a line that starts with any number of # s. Only your first title will be appear in your slide. A title looks like:
# slide title
Anything that comes after the title will be put as text in your slide. Check out the example below to see this in action.
Current Limitations ¶
Boldface , italics and hypertext are not supported features of the Presentation API.
Display in Jupyter ¶
The function below generates HTML code to display the presentation in an iframe directly in Jupyter.
Simple Example ¶
https://plotly.com/~AdamKulidjian/3700/simple-pres/
Click on the presentation above and use left/right arrow keys to flip through the slides.
Insert Plotly Chart ¶
If you want to insert a Plotly chart into your presentation, all you need to do is write a line in your presentation that takes the form:
Plotly(url)
where url is a Plotly url. For example:
Plotly(https://plotly.com/~AdamKulidjian/3564)
The Plotly url lines should be written on a separate line after your title line. You can put as many images in your slide as you want, as the API will arrange them on the slide automatically, but it is highly encouraged that you use 4 OR FEWER IMAGES PER SLIDE . This will produce the cleanest look.
Useful Tip : For Plotly charts it is HIGHLY ADVISED that you use a chart that has layout['autosize'] set to True . If it is False the image may be cropped or only partially visible when it appears in the presentation slide.
https://plotly.com/~AdamKulidjian/3710/pres-with-plotly-chart/
Insert Web Images ¶
To insert an image from the web, insert the a Image(url) where url is the image url.
https://plotly.com/~AdamKulidjian/3702/pres-with-images/
Image Stretch ¶
If you want to ensure that your image maintains its original width:height ratio, include the parameter imgStretch=False in your pres.Presentation() function call.
https://plotly.com/~AdamKulidjian/3703/pres-with-no-imgstretch/
Insert Code Blocks ¶
The Presentations API also supports the insertion of blocks of code with various available langauges to choose from.
To instantiate a "code environment" in your string, place a ``` at the beginning of a line, followed by the name of the programming language you want your code block to be styled in. Then the next lines will be considered "code lines ". To close the "code environment" put another ``` at the end of the line For example:
The valid languages to choose from are: arecpp, cs, css, fsharp, go, haskell, java, javascript, jsx, julia, xml, matlab, php, python, r, ruby, scala, sql and yaml.
https://plotly.com/~AdamKulidjian/3704/pres-with-code/
Style Your Presentation ¶
The Presentations API currently has two styles to choose from: Martik and Moods . These themes are inspired by already existing PowerPoint Templates. Let's use the same markdown_string in the previous example but this time try the Martik style.
Transitions ¶
You can specify how your want your slides to transition to one another. Just like in the Plotly Presentation Application, there are 4 types of transitions: slide , zoom , fade and spin .
To apply any combination of these transition to a slide, just insert transitions at the top of the slide as follows:
transition: slide, zoom
Make sure that this line comes before any heading that you define in the slide, i.e. like this:
Add Thin Border Around Text Boxes ¶
Every slide has children , and each of these children have a style attribute. This style property is derived from the CSS element of the same name. Since you have the power of CSS to work with, you could customize text borders in your presentation if you want.
https://plotly.com/~AdamKulidjian/3709/pres-with-custom-css/
Reference ¶
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
- OverflowAI GenAI features for Teams
- OverflowAPI Train & fine-tune LLMs
- Labs The future of collective knowledge sharing
- About the company Visit the blog
Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Get early access and see previews of new features.
How do I make powerpoint play presentations/load up ppts automatically?
I was wondering how I can make a script load powerpoint file, advance slides automatically and put it on full screen. Is there a way to make windows do that? Can I just load powerpoint.exe and maybe use some sort of API/Pipe to give commands from another script.
To make a case: I'm making a script that automatically scans a folder in windows (using python) and loads up the powerpoint presentations and keeps playing them in order.
- This would probably be better suited for Stack Overflow. You should get some better responses there. – Josh Hunt Commented Oct 28, 2009 at 0:48
4 Answers 4
One solution for you would be to use the PowerPoint Viewer program instead. PPT Viewer is set to open a PowerPoint file straight away in Presentation mode.
Alternatively, you can use the argument /s to start Powerpoint.
This will be equivalent to telling PowerPoint to straight away open up in Presentation mode.
- To do this from Python, you would probably use the subprocess module. – Jason R. Coombs Commented Nov 15, 2009 at 12:41
- I did end up using this solution but used win32com to actually generate slides instead of going through the process of synchronizing these different slides.. – prasanna Commented Dec 1, 2009 at 5:45
As previously stated, this is more StackOverflow geared, but this can easily be achieved with Python and AutoHotkey .
On the Python side of things, as a general idea on how to go about this (I'm kind of rusty, beware!):
- Find files using os.walk()
- Append each to a list, then iterate over the list, opening each one with os.system("powerpoint.exe /s filename") . The next one should not open until the previous closes.
AutoHotkey wise:
- Once opened, use #IfWinActive to detect an open Powerpoint window, and send mouse clicks to change slides at a set interval
I don't know what you mean by "order", you'll have to determine that in your Python script. If you want them alphabetical, sort the list alphabetically then iterate. If you want them sorted by creation date, then sort by date and iterate and so on.
Save the file with the extension ".pps". That will make powerpoint open the file in presentation mode. The presentaion needs to designed to advance slides, else you will have to script that part.
If you want more control over the powerpoint slide, you could write something in VB.Net (or other .Net languages) according to this MS support article .
If you wanted direct control from Python, you could probably use pywin32 or comtypes to invoke directly the same interfaces as described in the MS article. My guess is this is the most powerful solution and would probably provide the smoothest transitions between presentations, but is probably a lot more work than using subprocess to call into PowerPoint.
Your Answer
Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more
Sign up or log in
Post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .
Not the answer you're looking for? Browse other questions tagged python powerpoint or ask your own question .
- The Overflow Blog
- This developer tool is 40 years old: can it be improved?
- Unpacking the 2024 Developer Survey results
- Featured on Meta
- We've made changes to our Terms of Service & Privacy Policy - July 2024
- Introducing an accessibility dashboard and some upcoming changes to display...
- Tag hover experiment wrap-up and next steps
Hot Network Questions
- How do the Fremen harvest spice?
- Connect electric cable with 4 wires to 3-prong 30 Amp 125-Volt/250-Volt outlet?
- The average of an infinite sequence
- Expected Value of random variable in terms of hazard function
- Vilna Gaon's commentary on מחצית השקל
- Does space dust fall on the roof of my house and if so can I detect it with a cheap home microscope?
- Points of multiplicative groups
- Why do many CVT cars appear to index gears during normal automatic operation?
- Addressing Potential JavaScript Injection Vulnerabilities
- Can I say "he lived in silk" to mean he had a luxury life in which he was pampered with luxurious things?
- What was the price of bottled water, and road maps, in 1995? More generally, how to find such historic prices
- Old story about the shape of a robot and its ability to not break down
- Count number display: "99+" vs full number
- “Ryan was like, ‘Listen, if we need cue cards…’ and I was like, ‘Cue cards? I’m showing up off-book,'” Evans recounted
- How to output the number of polygons in each face of a classic flat body?
- Selecting 2 largest elements out of 4, preserving order
- Why did all countries converge on the exact same rules for voting (no poll tax, full suffrage, no maximum age, etc)?
- How to measure out fresh herbs when the recipe calls for 'a tablespoon of chopped herb'?
- Groups killed by centralizing one element
- Does the input of a CD4016 need to be baised?
- Is Heaven real?
- Word/phrase for avoiding a task because it has a lot of unknowns
- Public flight from Quito (UIO) to Lago Agrio Airport (LGQ)
- What does the circuit shown in the picture do?
IMAGES
VIDEO
COMMENTS
Installation: Open the command prompt on your system and write given below command: pip install python-pptx. Let's see some of its usage: Example 1: Creating new PowerPoint file with title and subtitle slide. Python3. from pptx import Presentation .
Here is the start of the function that we use to create our output PowerPoint: def create_ppt(input, output, report_data, chart): """ Take the input powerpoint file and use it as the template for the output file. """ prs = Presentation(input) # Use the output from analyze_ppt to understand which layouts and placeholders # to use # Create a ...
Step 3 - Generate PowerPoint Slides. Navigate to the directory containing the script in your terminal and run the following command: $ python3 create_ppt.py. This command will execute the script, and generate a new PowerPoint file named " Linux_Security_Presentation.pptx " in the same directory.
For this example, I created a simple bar chart in Python using a public Airbnb dataset for Asheville, NC. The python-pptx can control almost every element in PowerPoint that is available when working with PowerPoint directly. It is possible to start with a PowerPoint template, an existing presentation, or create the entire presentation.
Create interactive slides with Python in 8 Jupyter Notebook cells. Creating presentations in Jupyter Notebook is a great alternative to manually updating slides in other presentation creation software. If your data changes, you just re-execute the cell and slide chart is updated. Jupyter Notebook is using Reveal.js (opens in a new tab) for ...
To use a template in Python, you'll need to load an existing presentation as a template. You can do this using the following code: template = Presentation('template.pptx') presentation = Presentation(template) This code loads the presentation template.pptx and creates a new presentation based on that template.
In this tutorial I will be showing you how to create POWERPOINT PRESENTATIONS using only Python. This tutorial provides a step-by-step walk-through made to h...
And later it was used by a team to create ppt from it. And for this, I was using Python. With pptx I just automate the PowerPoint creation. So every time the scheduler ran the python script to manipulate the raw data and do the calculation it starts creating the presentation itself. So the other team just needs to download the ppt and send it ...
Working with Presentations¶. python-pptx allows you to create new presentations as well as make changes to existing ones. Actually, it only lets you make changes to existing presentations; it's just that if you start with a presentation that doesn't have any slides, it feels at first like you're creating one from scratch.
RISE also works with Notebook widgets. Try creating a new cell with the following code: from ipywidgets import interact. def my_function(x): return x. # create a slider. interact(my_function, x=20) Now start the slideshow on that cell and try running the cell (SHIFT+ENTER). You should see something like this:
6. You can use python-pptx library. It is a Python library for creating and updating PowerPoint (.pptx) files. This includes: Round-trip any Open XML presentation (.pptx file) including all its elements Add slides Populate text placeholders, for example to create a bullet slide Add image to slide at arbitrary position and size Add textbox to a ...
To upload the presentation online pass it through py.presentation_ops.upload(). In your string, use --- on a single line to seperate two slides. To put a title in your slide, put a line that starts with any number of # s. Only your first title will be appear in your slide. A title looks like: Anything that comes after the title will be put as ...
Method 4: Using Matplotlib with python-pptx. For those familiar with Matplotlib, this method involves creating a visual plot or chart with Matplotlib, saving it as an image, and then embedding the image into a PowerPoint slide using python-pptx. Here's an example: import matplotlib.pyplot as plt.
Here is a list of features provided by the python-pptx library: Create Presentations: Generate new PowerPoint presentations or modify existing ones. Slide Layouts: Choose from a variety of predefined slide layouts to structure your presentation. Text Handling: Add titles, subtitles, bullet points, and various text elements to slides. ...
Throughout this walkthrough, we'll be using the python-pptx package. This package supports different python versions ranging from 2.6 to 3.6. So, make sure you have the right version of Python installed on your computer first. Next, open your terminal and type −. pip install python-pptx.
To use Plotly's Presentations API you will write your presentation code in a string of markdown and then pass that through the Presentations API function pres.Presentation(). This creates a JSON version of your presentation. To upload the presentation online pass it through py.presentation_ops.upload(). In your string, use --- on a single line ...
One solution for you would be to use the PowerPoint Viewer program instead. PPT Viewer is set to open a PowerPoint file straight away in Presentation mode. Alternatively, you can use the argument /s to start Powerpoint. "powerpoint.exe /s <filename>.ppt". This will be equivalent to telling PowerPoint to straight away open up in Presentation mode.