Powerpoint Presentations(PPT) with Python


Powerpoint Presentations(PPT) with Python

In this article, Iam going to explain how you guys create your PPT with a automate program which is used in python.This type of programs are very easy and mostly used in mostly companies.

But guys first you have to know the basics of python, it is important to understand and learn the code easily.


If you want help and want to learn python basics click here :-


https://www.tech-programmer.com/2020/03/python-basics.html


Introduction

Today PowerPoint(PPT) is very famous and mostly used in python. In this article Iam not going to tell you any merits and demerits of PowerPoint(PPT) but will going to told how you guys leave thosesome old ways to create PowerPoint but use the  automating the creation of PowerPoint slides using python.

Now we are going touse an excellent python library for creating, updating and manipulating PowerPoint files: python-pptx. This python-pptx API is very usefull to create powerpoint and it is well documented and it is very easy to use.

There are very intresting part and we are  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 going to show you guys through an example of reading in and analyzing some Excel data with some external python libraries like pandas and then we are  creating tables and building a graph that can be implemented in a PowerPoint file with python programming language.


Python-pptx Introduction

Python-pptx are used in python projects and  could be create blank PowerPoint files but most of the  peoples are going to use or working with a predefined template that you can customized. Python-pptx’s API is very supportive and In this process quite simply and you guys could see your eyes how usefull it is and  these things use your template same as you use predefined templates.

Before we are going to start our some code samples or examples, there are two key components you need to understand first, because it is important : 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  and there is one placeholder on the slide at index.



In this image, we use Layout for a completely different look.

 
In order to make you guys easier to undersatnd Iam using or starting with your own templates, We created a simple python script that takes  a simple blank template and using it up with the various usefull elements.



We will could not or it is not possible to explain all the codes line by line but you could see my PPT.py program which uses python and how we will done it . Here is the python function which does the bulk of the works :-

def PPT_PY(input, output):

ppt = Presentation(input)

for i, _ in enumerate(ppt.slide_layouts):
slide = ppt.slides.add_slide(ppt.slide_layouts[i])

try:
title = slide.shapes.title
title.text = 'Title for Layout {}'.format(i)
except AttributeError:
print("No Title for Layout {}".format(i))

for z in slide.placeholders:
if z.is_placeholder:
pppt1 = z.placeholder_format

try:
if 'Title' not in z.text:
z.text = 'Placeholder index:{} type:{}'.format(ppt1.idx, z.name)
except AttributeError:
print("{} has no attribute in text".format(ppt1.type))
print('{} {}'.format(ppt1.idx, z.name))
ppt1.save(output)
The working flow or the  basic flow of this python program function is to loop through and create an example of the contentswith every layout included in the source PowerPoint file. Then on each and every slide, it will create the title.
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 by yourself on your home then see below:-

$ python3PPT_PYt.py simple-template.ppt

Creating your own PowerPoint(PPT)

For achieve our  dataset’s and analysis, I will be replicating the analysis in Generating Excel Reports from a Pandas Pivot Table. This article explain you that the pandas data manipulation in more detail so it will be helpful to make sure you are comfortable with it Iam not going deeper butwe have to understand the concept into the code.

Let’s get things started with the inputs and basic shell of the python program:-

from pptx import Presentation
from pptx.util import Inches
import argparse
import pandas as pd
import numpy as np
from datetime import date
import matplotlib.pyplot as plt
import seaborn as sea


if __name__ == "__main__":
value = parse_args()
value1 = pd.read_excel(value.report.name)
data = create_pivot(value1)
create_chart(value1, "image.png")
create_ppt(value.infile.name, value.outfile.name, data, "image.png")
After we create and understand  our command line value, we read the source PPT file into a pandas DataFrame. Next, we use that DataFrame as an input to create the Pivot_table codes are given below:-

def create(value, list=["Manager", "Rep", "Product"],
report_list=["Price", "Quantity"]):

table = pd.pivot_table(value, index=list,
values=report_list,
func=[np.sum, np.mean], fill_value=0)
return table
see again the Generating Excel Reports from a Pandas Pivot Table if this does not understanding to you.
The next step of our coding is creating a simple bar chart of sales performance used by the business :-

def chart(value, file_name):

value['total'] = value['Price'] * value['Quantity']
plot = value.groupby('Name')['total'].sum().order().plot(kind='barh')
figure = plot.get_figure()

figure.set_size_inches(6, 6)
figure.savefig(file_name, bbox_inches='tight', dpi=600)
Here is a scaled down version of the image:

We have completed the chart and a pivot table and Now we are going to implement our information into our new PowerPoint(PPT) file based on a our own given PowerPoint template file.

Before I go further we have to remind some things, there are a couple of things to learn. You need to know what layout you would like to use as well as where you want to use your content. If we looking our created PPT.py we know that the title slide is layout and that it has a title attribute and a subtitle at placeholder.

Here is the start of the function that we use to create our output PowerPoint in python:-

def PPT(value, args, data, chart):

x = Presentation(input)

layout = x.slide_layouts[0]
slide = x.slides.add_slide(layout)
title = slide.shapes.title
subtitle = slide.placeholders[1]
title.text = "Report Generated"
subtitle.text = "Generated on {:%m-%d-%Y}".format(date.today())
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:

Looking nice na?

The next step is to implement our picture into oue slide.
From our previous analysis, we know that the graph slide we want to use is layout index, so we create a new slide, add a title then add a picture into placeholder. The final step adds a subtitle at placeholder.

layout = value.slide_layouts[8]
slide = value.slides.add_slide(layout)
title = slide.shapes.title
title.text = "Report of the busssiness"
placeholder = slide.placeholders[1]
image = placeholder.insert_picture(chart)
subtitle = slide.placeholders[2]
subtitle.text = "Results came of all our analysis"
Here is our masterpiece:

For the final portion of the presentation, we will create a table for each manager with their sales performance report.
Here is an image of what we’re going to achieve:

WE have created our poerpoint(PPT) in python but we have a good and bad news. The good news is that there is an python_pptx 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.

Our program or our code takes a DataFrame and converts it to a PowerPoint(PPT) table. I have taken the liberty of including a portion of it in my script.

for rob in data.index.get_level_values(0).unique():
slide = value.slides.add_slide(prs.slide_layouts[2])
title = slide.shapes.title
title.text = "Report for {}".format(rob)
top = Inches(1.5)
left = Inches(0.25)
width = Inches(9.25)
height = Inches(5.0)

df_to_table(slide, data.xs(rob, level=0).reset_index(),
left, top, width, height)
value.save(args)
The code takes each manager out of the pivot table and builds a simple DataFrame that containsall the details of the 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:-

$ python3 PPT.py simple-template.pptx detail.xlsx report.pptx
 

Conclusion

I really enjoy you guys to explain about python and how you all guys could create your own automating python program.I know that iam not explaing all the thing and anyone cannot explain it on only one article but I will told almost everything that is usefull for every developer and after read this article they can use it in there projects.

Well mostly Powerpoint(PPT) used by biggest bussiness companies because they need them for there daily uses in their work and these type of programs help them to save time.so, kindly this article will help you all the guys.

Keep this article in mind and create a your program in python programming language.

If you Guy’s like this article plz comment here or if you all want solutions of some problems then comment  . . . . .

Reactions

Post a Comment

0 Comments