Document Operation

Document Operation (16)

Python Read PowerPoint Documents

PowerPoint (PPT & PPTX) files are rich with diverse content, including text, images, tables, charts, shapes, and metadata. Extracting these elements programmatically can unlock a wide range of use cases, from automating repetitive tasks to performing in-depth data analysis or migrating content across platforms.

In this tutorial, we'll explore how to read PowerPoint documents in Python using Spire.Presentation for Python, a powerful library for processing PowerPoint files.

Table of Contents:

1. Python Library to Read PowerPoint Files

To work with PowerPoint files in Python, we'll use Spire.Presentation for Python. This feature-rich library enables developers to create, edit, and read content from PowerPoint presentations efficiently. It allows for the extraction of text, images, tables, SmartArt, and metadata with minimal coding effort.

Before we begin, install the library using pip:

pip install spire.presentation

Now, let's dive into different ways to extract content from PowerPoint files.

2. Extracting Text from Slides in Python

PowerPoint slides contain text in various forms—shapes, tables, SmartArt, and more. We'll explore how to extract text from each of these elements.

2.1 Extract Text from Shapes

Most text in PowerPoint slides resides within shapes (text boxes, labels, etc.). Here’s how to extract text from shapes:

Steps-by-Step Guide

  • Initialize the Presentation object and load your PowerPoint file.
  • Iterate through each slide and its shapes.
  • Check if a shape is an IAutoShape (a standard text container).
  • Extract text from each paragraph in the shape.

Code Example

from spire.presentation import *
from spire.presentation.common import *

# Create an object of Presentation class
presentation = Presentation()

# Load a PowerPoint presentation
presentation.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.pptx")

# Create a list
text = []

# Loop through the slides in the document
for slide_index, slide in enumerate(presentation.Slides):
    # Add slide marker
    text.append(f"====slide {slide_index + 1}====")

    # Loop through the shapes in the slide
    for shape in slide.Shapes:
        # Check if the shape is an IAutoShape object
        if isinstance(shape, IAutoShape):
            # Loop through the paragraphs in the shape
            for paragraph in shape.TextFrame.Paragraphs:
                # Get the paragraph text and append it to the list
                text.append(paragraph.Text)

# Write the text to a txt file
with open("output/ExtractAllText.txt", "w", encoding='utf-8') as f:
    for s in text:
        f.write(s + "\n")

# Dispose resources
presentation.Dispose()

Output:

A text file containing all extracted text from shapes in the presentation.

2.2 Extract Text from Tables

Tables in PowerPoint store structured data. Extracting this data requires iterating through each cell to maintain the table’s structure.

Step-by-Step Guide

  • Initialize the Presentation object and load your PowerPoint file.
  • Iterate through each slide to access its shapes.
  • Identify table shapes (ITable objects).
  • Loop through rows and cells to extract text.

Code Example

from spire.presentation import *
from spire.presentation.common import *

# Create a Presentation object
presentation = Presentation()

# Load a PowerPoint file
presentation.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.pptx")

# Create a list for tables
tables = []

# Loop through the slides
for slide in presentation.Slides:
    # Loop through the shapes in the slide
    for shape in slide.Shapes:
        # Check whether the shape is a table
        if isinstance(shape, ITable):
            tableData = ""

            # Loop through the rows in the table
            for row in shape.TableRows:
                rowData = ""

                # Loop through the cells in the row
                for i in range(row.Count):
                    # Get the cell value
                    cellValue = row[i].TextFrame.Text
                    # Add cell value with spaces for better readability
                    rowData += (cellValue + "  |  " if i < row.Count - 1 else cellValue)
                tableData += (rowData + "\n")
            tables.append(tableData)

# Write the tables to text files
for idx, table in enumerate(tables, start=1):
    fileName = f"output/Table-{idx}.txt"
    with open(fileName, "w", encoding='utf-8') as f:
        f.write(table)

# Dispose resources
presentation.Dispose()

Output:

A text file containing structured table data from the presentation.

2.3 Extract Text from SmartArt

SmartArt is a unique feature in PowerPoint used for creating diagrams. Extracting text from SmartArt involves accessing its nodes and retrieving the text from each node.

Step-by-Step Guide

  • Load the PowerPoint file into a Presentation object.
  • Iterate through each slide and its shapes.
  • Identify ISmartArt shapes in slides.
  • Loop through each node in the SmartArt.
  • Extract and save the text from each node.

Code Example

from spire.presentation.common import *
from spire.presentation import *

# Create a Presentation object
presentation = Presentation()

# Load a PowerPoint file
presentation.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.pptx")

# Iterate through each slide in the presentation
for slide_index, slide in enumerate(presentation.Slides):

    # Create a list to store the extracted text for the current slide
    extracted_text = []

    # Loop through the shapes on the slide and find the SmartArt shapes
    for shape in slide.Shapes:
        if isinstance(shape, ISmartArt):
            smartArt = shape
            
            # Extract text from the SmartArt nodes and append to the list
            for node in smartArt.Nodes:
                extracted_text.append(node.TextFrame.Text)

    # Write the extracted text to a separate text file for each slide
    if extracted_text:  # Only create a file if there's text extracted
        file_name = f"output/SmartArt-from-slide-{slide_index + 1}.txt"
        with open(file_name, "w", encoding="utf-8") as text_file:
            for text in extracted_text:
                text_file.write(text + "\n")

# Dispose resources
presentation.Dispose()

Output:

A text file containing node text of a SmartArt.

You might also be interested in: Read Speaker Notes in PowerPoint in Python

3. Saving Images from Slides in Python

In addition to text, slides often contain images that may be important for your analysis. This section will show you how to save images from the slides.

Step-by-Step Guide

  • Initialize the Presentation object and load your PowerPoint file.
  • Access the Images collection in the presentation.
  • Iterate through each image and save it in a desired format (e.g., PNG).

Code Example

from spire.presentation.common import *
from spire.presentation import *

# Create a Presentation object
presentation = Presentation()

# Load a PowerPoint document
presentation.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.pptx")

# Get the images in the document
images = presentation.Images

# Iterate through the images in the document
for i, image in enumerate(images):

    # Save a certain image in the specified path
    ImageName = "Output/Images_"+str(i)+".png"
    image.Image.Save(ImageName)

# Dispose resources
presentation.Dispose()

Output:

PNG files of all images extracted from the PowerPoint.

4. Accessing Metadata (Document Properties) in Python

Extracting metadata provides insights into the presentation, such as its title, author, and keywords. This section will guide you on how to access and save this metadata.

Step-by-Step Guide

  • Create and load your PowerPoint file into a Presentation object.
  • Access the DocumentProperty object.
  • Extract properties like Title , Author , and Keywords .

Code Example

from spire.presentation.common import *
from spire.presentation import *

# Create a Presentation object
presentation = Presentation()

# Load a PowerPoint document
presentation.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.pptx")

# Get the DocumentProperty object
documentProperty = presentation.DocumentProperty

# Prepare the content for the text file
properties = [
    f"Title: {documentProperty.Title}",
    f"Subject: {documentProperty.Subject}",
    f"Author: {documentProperty.Author}",
    f"Manager: {documentProperty.Manager}",
    f"Company: {documentProperty.Company}",
    f"Category: {documentProperty.Category}",
    f"Keywords: {documentProperty.Keywords}",
    f"Comments: {documentProperty.Comments}",
]

# Write the properties to a text file
with open("output/DocumentProperties.txt", "w", encoding="utf-8") as text_file:
    for line in properties:
        text_file.write(line + "\n")

# Dispose resources
presentation.Dispose()

Output:

A text file containing PowerPoint document properties.

You might also be interested in: Add Document Properties to a PowerPoint File in Python

5. Conclusion

With Spire.Presentation for Python, you can effortlessly read and extract various elements from PowerPoint files—such as text, images, tables, and metadata. This powerful library streamlines automation tasks, content analysis, and data migration, allowing for efficient management of PowerPoint files. Whether you're developing an analytics tool, automating document processing, or managing presentation content, Spire.Presentation offers a robust and seamless solution for programmatically handling PowerPoint files.

6. FAQs

Q1. Can Spire.Presentation handle password-protected PowerPoint files?

Yes, Spire.Presentation can open and process password-protected PowerPoint files. To access an encrypted file, use the LoadFromFile() method with the password parameter:

presentation.LoadFromFile("encrypted.pptx", "yourpassword")

Q2. How can I read comments from PowerPoint slides?

You can read comments from PowerPoint slides using the Spire.Presentation library. Here’s how:

from spire.presentation import Presentation

presentation = Presentation()
presentation.LoadFromFile("Input.pptx")

with open("PowerPoint_Comments.txt", "w", encoding="utf-8") as file:
    for slide_idx, slide in enumerate(presentation.Slides):
        if len(slide.Comments) > 0:
            for comment_idx, comment in enumerate(slide.Comments):
                file.write(f"Comment {comment_idx + 1} from Slide {slide_idx + 1}: {comment.Text}\n")

Q3. Does Spire.Presentation preserve formatting when extracting text?

Basic text extraction retrieves raw text content. For formatted text (fonts, colors), you would need to access additional properties like TextRange.LatinFont and TextRange.Fill .

Q4. Are there any limitations on file size when reading PowerPoint files in Python?

While Spire.Presentation can handle most standard presentations, extremely large files (hundreds of MB) may require optimization for better performance.

Q5. Can I create or modify PowerPoint documents using Spire.Presentation?

Yes, you can create PowerPoint documents and modify existing ones using Spire.Presentation. The library provides a range of features that allow you to add new slides, insert text, images, tables, and shapes, as well as edit existing content.

Get a Free License

To fully experience the capabilities of Spire.Presentation for Python without any evaluation limitations, you can request a free 30-day trial license.

Python code examples for creating PowerPoint documents

Creating PowerPoint presentations programmatically can save time and enhance efficiency in generating reports, slideshows, and other visual presentations. By automating the process, you can focus on content and design rather than manual formatting.

In this tutorial, we will explore how to create PowerPoint documents in Python using Spire.Presentation for Python. This powerful tool allows developers to manipulate and generate PPT and PPTX files seamlessly.

Table of Contents:

1. Python Library to Work with PowerPoint Files

Spire.Presentation is a robust library for creating, reading, and modifying PowerPoint files in Python , without requiring Microsoft Office. This library supports a wide range of features, including:

  • Create PowerPoint documents from scratch or templates.
  • Add text, images, lists, tables, charts, and shapes.
  • Customize fonts, colors, backgrounds, and layouts.
  • Save as or export to PPT, PPTX, PDF, or images.

In the following sections, we will walk through the steps to install the library, create presentations, and add various elements to your slides.

2. Installing Spire.Presentation for Python

To get started, you need to install the Spire.Presentation library. You can install it using pip:

pip install spire.presentation

Once installed, you can begin utilizing its features in your Python scripts to create PowerPoint documents.

3. Creating a PowerPoint Document from Scratch

3.1 Generate and Save a Blank Presentation

Let's start by creating a basic PowerPoint presentation from scratch. The following code snippet demonstrates how to generate and save a blank presentation:

from spire.presentation.common import *
from spire.presentation import *

# Create a Presentation object
presentation = Presentation()

# Set the slide size type
presentation.SlideSize.Type = SlideSizeType.Screen16x9

# Add a slide (there is one slide in the document by default)
presentation.Slides.Append()

# Save the document as a PPT or PPTX file
presentation.SaveToFile("BlankPowerPoint.pptx", FileFormat.Pptx2019)
presentation.Dispose()

In this code:

  • Presentation : Root class representing the PowerPoint file.
  • SlideSize.Type : Sets the slide dimensions (e.g., SlideSizeType.Screen16x9 for widescreen).
  • Slides.Append() : Adds a new slide to the presentation. By default, a presentation starts with one slide.
  • SaveToFile() : Saves the presentation to the specified file format (PPTX in this case).

3.2 Add Basic Elements to Your Slides

Now that we have a blank presentation, let's add some basic elements like text, images, lists, and tables.

Add Formatted Text

To add formatted text, we can use the following code:

# Get the first slide
first_slide = presentation.Slides[0]

# Add a shape to the slide
rect = RectangleF.FromLTRB (30, 60, 900, 150)
shape = first_slide.Shapes.AppendShape(ShapeType.Rectangle, rect)
shape.ShapeStyle.LineColor.Color = Color.get_Transparent()
shape.Fill.FillType = FillFormatType.none

# Add text to the shape
shape.AppendTextFrame("This guide demonstrates how to create a PowerPoint document using Python.")

# Get text of the shape as a text range
textRange = shape.TextFrame.TextRange

# Set font name, style (bold & italic), size and color
textRange.LatinFont = TextFont("Times New Roman")
textRange.IsBold = TriState.TTrue
textRange.FontHeight = 32
textRange.Fill.FillType = FillFormatType.Solid
textRange.Fill.SolidColor.Color = Color.get_Black()

# Set alignment
textRange.Paragraph.Alignment = TextAlignmentType.Left

In this code:

  • AppendShape() : Adds a shape to the slide. We create a rectangle shape that will house our text.
  • AppendTextFrame() : Adds a text frame to the shape, allowing us to insert text into it.
  • TextFrame.TextRange : Accesses the text range of the shape, enabling further customization such as font style, size, and color.
  • Paragraph.Alignment : Sets the alignment of the text within the shape.

Add an Image

To include an image in your presentation, use the following code snippet:

# Get the first slide
first_slide = presentation.Slides[0]

# Load an image file
imageFile = "C:\\Users\\Administrator\\Desktop\\logo.png"
stream = Stream(imageFile)
imageData = presentation.Images.AppendStream(stream)

# Reset size
width = imageData.Width * 0.6
height = imageData.Height * 0.6

# Append it to the slide
rect = RectangleF.FromLTRB (750, 50, 750 + width, 50 + height)
image = first_slide.Shapes.AppendEmbedImageByImageData(ShapeType.Rectangle, imageData, rect)
image.Line.FillType = FillFormatType.none

In this code:

  • Stream() : Creates a stream from the specified image file path.
  • AppendStream() : Appends the image data to the presentation's image collection.
  • AppendEmbedImageByImageData() : Adds the image to the slide at the specified rectangle coordinates.

You may also like: Insert Shapes in PowerPoint in Python

Add a List

To add a bulleted list to your slide, we can use:

# Get the first slide
first_slide = presentation.Slides[0]

# Specify list bounds and content
listBounds = RectangleF.FromLTRB(30, 150, 500, 350)
listContent = [
    " Step 1. Install Spire.Presentation for Python.",
    " Step 2. Create a Presentation object.",
    " Step 3. Add text, images, etc. to slides.",
    " Step 5. Set a background image or color.",
    " Step 6. Save the presentation to a PPT(X) file."
]

# Add a shape
autoShape = first_slide.Shapes.AppendShape(ShapeType.Rectangle, listBounds)
autoShape.TextFrame.Paragraphs.Clear()
autoShape.Fill.FillType = FillFormatType.none
autoShape.Line.FillType = FillFormatType.none

for content in listContent:
    # Create paragraphs based on the list content and add them to the shape
    paragraph = TextParagraph()
    autoShape.TextFrame.Paragraphs.Append(paragraph)
    paragraph.Text = content
    paragraph.TextRanges[0].Fill.FillType = FillFormatType.Solid
    paragraph.TextRanges[0].Fill.SolidColor.Color = Color.get_Black()
    paragraph.TextRanges[0].FontHeight = 20
    paragraph.TextRanges[0].LatinFont = TextFont("Arial")

    # Set the bullet type for these paragraphs
    paragraph.BulletType = TextBulletType.Symbol

    # Set line spacing
    paragraph.LineSpacing = 150

In this code:

  • AppendShape() : Creates a rectangle shape for the list.
  • TextFrame.Paragraphs.Append() : Adds paragraphs for each list item.
  • BulletType : Sets the bullet style for the list items.

Add a Table

To include a table, you can use the following:

# Get the first slide
first_slide = presentation.Slides[0]

# Define table dimensions and data
widths = [200, 200, 200]
heights = [18, 18, 18, 18]
dataStr = [
    ["Slide Number", "Title", "Content Type"], 
    ["1", "Introduction", "Text/Image"], 
    ["2", "Project Overview", "Chart/Graph"],  
    ["3", "Key Findings", "Text/List"]
]

# Add table to the slide
table = first_slide.Shapes.AppendTable(30, 360, widths, heights)

# Fill table with data and apply formatting
for rowNum, rowData in enumerate(dataStr):
    for colNum, cellData in enumerate(rowData):  
        cell = table[colNum, rowNum]
        cell.TextFrame.Text = cellData
        
        textRange = cell.TextFrame.Paragraphs[0].TextRanges[0]
        textRange.LatinFont = TextFont("Times New Roman")
        textRange.FontHeight = 20
        
        cell.TextFrame.Paragraphs[0].Alignment = TextAlignmentType.Center

# Apply a built-in table style
table.StylePreset = TableStylePreset.MediumStyle2Accent1

In this code:

  • AppendTable() : Adds a table to the slide at specified coordinates with defined widths and heights for columns and rows.
  • Cell.TextFrame.Text : Sets the text for each cell in the table.
  • StylePreset : Applies a predefined style to the table for enhanced aesthetics.

3.3 Apply a Background Image or Color

To set a custom background for your slide, use the following code:

# Get the first slide
first_slide = presentation.Slides[0]

# Get the background of the first slide
background = first_slide.SlideBackground

# Create a stream from the specified image file
stream = Stream("C:\\Users\\Administrator\\Desktop\\background.jpg")
imageData = presentation.Images.AppendStream(stream)

# Set the image as the background 
background.Type = BackgroundType.Custom
background.Fill.FillType = FillFormatType.Picture
background.Fill.PictureFill.FillType = PictureFillType.Stretch
background.Fill.PictureFill.Picture.EmbedImage = imageData

In this code:

  • SlideBackground : Accesses the background properties of the slide.
  • Fill.FillType : Specifies the type of fill (in this case, an image).
  • PictureFill.FillType : Sets how the background image is displayed (stretched, in this case).
  • Picture.EmbedImage : Sets image data for the background.

For additional background options, refer to this tutorial: Set Background Color or Picture for PowerPoint Slides in Python

Output:

Below is a screenshot of the PowerPoint document generated by the code snippets provided above.

Create a PowerPoint file from scratch in Python

4. Creating PowerPoint Documents Based on a Template

Using templates can simplify the process of creating presentations by allowing you to replace placeholders with actual data. Below is an example of how to create a PowerPoint document based on a template:

from spire.presentation.common import *
from spire.presentation import *

# Create a Presentation object
presentation = Presentation()

# Load a PowerPoint document from a specified file path
presentation.LoadFromFile("C:\\Users\\Administrator\\Desktop\\template.pptx")

# Get a specific slide from the presentation
slide = presentation.Slides[0]

# Define a list of replacements where each tuple consists of the placeholder and its corresponding replacement text
replacements = [
    ("{project_name}", "GreenCity Solar Initiative"),
    ("{budget}", "$1,250,000"),
    ("{status}", "In Progress (65% Completion)"),
    ("{start_date}", "March 15, 2023"),
    ("{end_date}", "November 30, 2024"),
    ("{manager}", "Emily Carter"),
    ("{client}", "GreenCity Municipal Government")
]

# Iterate through each replacement pair
for old_string, new_string in replacements:

    # Replace the first occurrence of the old string in the slide with the new string
    slide.ReplaceFirstText(old_string, new_string, False)

# Save the modified presentation to a new file
presentation.SaveToFile("Template-Based.pptx", FileFormat.Pptx2019)
presentation.Dispose()

In this code:

  • LoadFromFile() : Loads an existing PowerPoint file that serves as the template.
  • ReplaceFirstText() : Replaces placeholders within the slide with actual values. This is useful for dynamic content generation.
  • SaveToFile() : Saves the modified presentation as a new file.

Output:

Create PowerPoint documents based on a template in Python

5. Best Practices for Python PowerPoint Generation

When creating PowerPoint presentations using Python, consider the following best practices:

  • Maintain Consistency : Ensure that the formatting (fonts, colors, styles) is consistent across slides for a professional appearance.
  • Modular Code: Break document generation into functions (e.g., add_list(), insert_image()) for reusability.
  • Optimize Images : Resize and compress images before adding them to presentations to reduce file size and improve loading times.
  • Use Templates : Whenever possible, use templates to save time and maintain a cohesive design.
  • Test Your Code : Always test your presentation generation code to ensure that all elements are added correctly and appear as expected.

6. Wrap Up

In this tutorial, we explored how to create PowerPoint documents in Python using the Spire.Presentation library. We covered the installation, creation of presentations from scratch, adding various elements, and using templates for dynamic content generation. With these skills, you can automate the creation of presentations, making your workflow more efficient and effective.

7. FAQs

Q1. What is Spire.Presentation?

Spire.Presentation is a powerful library used for creating, reading, and modifying PowerPoint files in various programming languages, including Python.

Q2. Does this library require Microsoft Office to be installed?

No, Spire.Presentation operates independently and does not require Microsoft Office.

Q3. Can I customize the layout of slides in my presentation?

Yes, you can customize the layout of each slide by adjusting properties such as size, background, and the placement of shapes, text, and images.

Q4. Does Spire.Presentation support both PPT and PPTX format?

Yes, Spire.Presentation supports both PPT and PPTX formats, allowing you to create and manipulate presentations in either format.

Q5. Can I add charts to my presentations?

Yes, Spire.Presentation supports the addition of charts to your slides, allowing you to visualize data effectively. For detailed instruction, refer to: How to Create Column Charts in PowerPoint Using Python

Get a Free License

To fully experience the capabilities of Spire.Presentation for Python without any evaluation limitations, you can request a free 30-day trial license.

PowerPoint presentations are a powerful tool for presenting information in an organized and engaging manner. To further enhance the organization of slides, PowerPoint allows users to group slides into sections. This feature makes navigating and managing large presentations much easier. In this article, we'll show you how to manage slides within PowerPoint sections in Python using Spire.Presentation for Python. Specifically, we'll cover how to add, retrieve, reorder, and remove slides in these sections.

Install Spire.Presentation for Python

This scenario requires Spire.Presentation for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.

pip install Spire.Presentation

If you are unsure how to install, please refer to this tutorial: How to Install Spire.Presentation for Python on Windows

Insert Slides into a PowerPoint Section in Python

Inserting slides is essential when you want to introduce new content to a section. Using Spire.Presentation for Python, you can quickly insert a slide into a section with the Section.Insert() method. The detailed steps are as follows.

  • Create an instance of the Presentation class.
  • Load a PowerPoint presentation using the Presentation.LoadFromFile() method.
  • Get a specific section through its index (0-based) using the Presentation.SectionList(index) property.
  • Add a new slide to the presentation, then insert it into the section using the Section.Insert() method.
  • Remove the added slide from the presentation.
  • Save the resulting presentation using the Presentation.SaveToFile() method.
  • Python
from spire.presentation import *

# Create an instance of the Presentation class
presentation = Presentation()
# Load a PowerPoint presentation
presentation.LoadFromFile("Example.pptx")

# Access the first section
first_section = presentation.SectionList[0]

# Add a new slide to the presentation and insert it at the start of the section
slide = presentation.Slides.Append()
first_section.Insert(0, slide)

# Remove the added slide from the presentation
presentation.Slides.Remove(slide)

# Save the modified presentation
presentation.SaveToFile("InsertSlidesInSection.pptx", FileFormat.Pptx2016)
# Close the Presentation object
presentation.Dispose()

Insert Slides into a PowerPoint Section in Python

Retrieve Slides from a PowerPoint Section in Python

Retrieving slides from a specific section allows you to focus on a smaller group of slides for tasks such as reordering or applying custom formatting. Using the Section.GetSlides() method in Spire.Presentation for Python, you can easily access all the slides in a particular section. The detailed steps are as follows.

  • Create an instance of the Presentation class.
  • Load a PowerPoint presentation using the Presentation.LoadFromFile() method.
  • Get a specific section through its index (0-based) using the Presentation.SectionList(index) property.
  • Retrieve the slides within the section using the Section.GetSlides() method.
  • Iterate through the retrieved slides and get the slide number (1-based) of each slide.
  • Python
from spire.presentation import *

# Create an instance of the Presentation class
presentation = Presentation()
# Load a PowerPoint presentation
presentation.LoadFromFile("Example.pptx")

# Retrieve the slides in the 3rd section
section = presentation.SectionList[2]
slides = section.GetSlides()

output_content = "The slide numbers in this section are:\n"

# Get the slide number of each slide in the section
for slide in slides:
    output_content += str(slide.SlideNumber) + " "

# Save the slide number to a text file
with open("slide_numbers.txt", "w") as file:
    file.write(output_content)

Retrieve Slides from a PowerPoint Section in Python

Reorder Slides in a PowerPoint Section in Python

Reordering slides is important to ensure related content is in the right order. Spire.Presentation for Python offers the Section.Move() method, which allows you to move a slide to a new position within a section. The detailed steps are as follows.

  • Create an instance of the Presentation class.
  • Load a PowerPoint presentation using the Presentation.LoadFromFile() method.
  • Get a specific section through its index (0-based) using the Presentation.SectionList(index) property.
  • Move a specific slide in the section to another position using the Section.Move() method.
  • Save the resulting presentation using the Presentation.SaveToFile() method.
  • Python
from spire.presentation import *

# Create an instance of the Presentation class
presentation = Presentation()
# Load a PowerPoint presentation
presentation.LoadFromFile("Example.pptx")

# Access the 3rd section
section = presentation.SectionList[2]

# Retrieve the slides in the section
slides = section.GetSlides()

# Move the 1st slide in the section to the specified position
section.Move(2, slides[0])

# Save the modified presentation
presentation.SaveToFile("ReorderSlidesInSection.pptx", FileFormat.Pptx2016)
# Close the Presentation object
presentation.Dispose()

Reorder Slides in a PowerPoint Section in Python

Remove Slides from a PowerPoint Section in Python

Removing slides from a section streamlines your presentation, particularly when some slides become outdated or unnecessary. With Spire.Presentation for Python, you can easily remove a single slide or multiple slides from a section using the Section.RemoveAt() or Section.RemoveRange() method. The detailed steps are as follows.

  • Create an instance of the Presentation class.
  • Load a PowerPoint presentation using the Presentation.LoadFromFile() method.
  • Get a specific section through its index (0-based) using the Presentation.SectionList(index) property.
  • Remove a specific slide or a range of slides from the presentation using the Section.RemoveAt() or Section.RemoveRange() method.
  • Save the resulting presentation using the Presentation.SaveToFile() method.
  • Python
from spire.presentation import *

# Create an instance of the Presentation class
presentation = Presentation()
# Load a PowerPoint presentation
presentation.LoadFromFile("Example.pptx")

# Access the 3rd section
section = presentation.SectionList[2]

# Remove the first slide from the section
section.RemoveAt(0)

# Or remove a range of slides from the section
# section.RemoveRange(0, 2)

# Save the modified presentation
presentation.SaveToFile("RemoveSlidesInSection.pptx", FileFormat.Pptx2016)
# Close the Presentation object
presentation.Dispose()

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Python: Split PowerPoint Presentations

2024-11-21 01:03:03 Written by Koohji

Splitting a PowerPoint presentation into smaller files or individual sections can be useful in various situations. For instance, when collaborating with a team, each member may only need a specific section of the presentation to work on. Additionally, breaking a large presentation into smaller parts can simplify sharing over email or uploading to platforms with file size restrictions. In this article, we'll show you how to split PowerPoint presentations by slides, slide ranges, and sections in Python using Spire.Presentation for Python.

Install Spire.Presentation for Python

This scenario requires Spire.Presentation for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.

pip install Spire.Presentation

If you are unsure how to install, please refer to this tutorial: How to Install Spire.Presentation for Python on Windows

Split PowerPoint Presentations by Slides in Python

Developers can use Spire.Presentation for Python to split a PowerPoint presentation into individual slides by iterating through the slides in the presentation and adding each slide to a new presentation. The detailed steps are as follows.

  • Create an instance of the Presentation class.
  • Load a PowerPoint presentation using the Presentation.LoadFromFile() method.
  • Iterate through all slides in the presentation:
    • Access the current slide through the Presentation.Slides[index] property.
    • Create a new PowerPoint presentation using the Presentation class and remove its default slide using the Presentation.Slides.RemoveAt(0) method.
    • Append the current slide to the new presentation using the Presentation.Slides.AppendBySlide() method.
    • Save the new presentation as a file using the ISlide.SaveToFile() method.
  • Python
from spire.presentation.common import *
from spire.presentation import *

# Create an instance of the Presentation class
presentation = Presentation()
# Load a PowerPoint presentation
presentation.LoadFromFile("Sample.pptx")

# Iterate through all slides in the presentation
for i in range(presentation.Slides.Count):
    # Get the current slide
    slide = presentation.Slides[i]
    
    # Create a new PowerPoint presentation and remove its default slide
    newPresentation = Presentation()
    newPresentation.Slides.RemoveAt(0)
    
    # Append the current slide to the new presentation
    newPresentation.Slides.AppendBySlide(slide)
    
    # Save the new presentation as a file
    newPresentation.SaveToFile(f"output/Presentations/Slide-{i + 1}.pptx", FileFormat.Pptx2013)    
    newPresentation.Dispose()

presentation.Dispose()

Split PowerPoint Presentations by Slides in Python

Split PowerPoint Presentations by Slide Ranges in Python

Apart from splitting a PowerPoint presentation into individual slides, developers can also divide it into specific ranges of slides by adding the desired slides to new presentations. The detailed steps are as follows.

  • Create an instance of the Presentation class.
  • Load a PowerPoint presentation using the Presentation.LoadFromFile() method.
  • Create new PowerPoint presentations using the Presentation class and remove the default slides within them using the Presentation.Slides.RemoveAt(0) method.
  • Append specified ranges of slides to the new presentations using the Presentation.Slides.AppendBySlide() method.
  • Save the new presentations as files using the Presentation.SaveToFile() method.
  • Python
from spire.presentation.common import *
from spire.presentation import *

# Create an instance of the Presentation class
presentation = Presentation()
# Load a PowerPoint presentation
presentation.LoadFromFile("Sample.pptx")

# Create two new PowerPoint presentations and remove their default slides
presentation1 = Presentation()
presentation2 = Presentation()
presentation1.Slides.RemoveAt(0)
presentation2.Slides.RemoveAt(0)

# Append slides 1-3 to the first new presentation
for i in range(3):
    presentation1.Slides.AppendBySlide(presentation.Slides[i])
# Append the remaining slides to the second new presentation
for i in range(3, presentation.Slides.Count):
    presentation2.Slides.AppendBySlide(presentation.Slides[i])

# Save the new presentations as files
presentation1.SaveToFile("output/Presentations/SlideRange1.pptx", FileFormat.Pptx2013)
presentation2.SaveToFile("output/Presentations/SlideRange2.pptx", FileFormat.Pptx2013)

presentation1.Dispose()
presentation2.Dispose()
presentation.Dispose()

Split PowerPoint Presentations by Slide Ranges in Python

Split PowerPoint Presentations by Sections in Python

Sections in PowerPoint are often used to organize slides into manageable groups. With Spire.Presentation for Python, developers can split a PowerPoint presentation into sections by iterating through the sections in the presentation and adding the slides within each section to a new presentation. The detailed steps are as follows.

  • Create an instance of the Presentation class.
  • Load a PowerPoint presentation using the Presentation.LoadFromFile() method.
  • Iterate through all sections in the presentation:
    • Access the current section through the Presentation.SectionList[] property.
    • Create a new PowerPoint presentation using the Presentation class and remove its default slide using the Presentation.Slides.RemoveAt(0) method.
    • Add a section to the new presentation with the same name using the Presentation.SectionList.Append() method.
    • Retrieve the slides of the current section using the Section.GetSlides() method.
    • Iterate through the retrieved slides and add them to the section of the new presentation using the Section.Insert() method.
    • Save the new presentation as a file using the Presentation.SaveToFile() method.
  • Python
from spire.presentation.common import *
from spire.presentation import *

# Create an instance of the Presentation class
presentation = Presentation()
# Load a PowerPoint presentation
presentation.LoadFromFile("Sample.pptx")

# Iterate through all sections
for i in range(presentation.SectionList.Count):
    # Get the current section
    section = presentation.SectionList[i]
    
    # Create a new PowerPoint presentation and remove its default slide
    newPresentation = Presentation()
    newPresentation.Slides.RemoveAt(0)
    # Add a section to the new presentation
    newSection = newPresentation.SectionList.Append(section.Name)
    
    # Retrieve the slides of the current section
    slides = section.GetSlides()
    
    # Insert each retrieved slide into the section of the new presentation
    for slide_index, slide in enumerate(slides):
        newSection.Insert(slide_index, slide)
    
    # Save the new presentation as a file
    newPresentation.SaveToFile(f"output/Presentations/Section-{i + 1}.pptx", FileFormat.Pptx2019)
    newPresentation.Dispose()

presentation.Dispose()

Split PowerPoint Presentations by Sections in Python

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

A well-chosen background can enhance a presentation's appeal, but overly elaborate colors or images may distract viewers and obscure the main message. Additionally, when reusing templates, the original background may not suit the new content. In these cases, removing the background becomes essential to keep your slides clear and focused. This article will show you how to remove backgrounds from PowerPoint slides or slide masters in Python with Spire.Presentation for Python, giving you the flexibility to create clean, professional presentations that keep the audience's attention on what matters.

Install Spire.Presentation for Python

This scenario requires Spire.Presentation for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.

pip install Spire.Presentation

If you are unsure how to install, please refer to this tutorial: How to Install Spire.Presentation for Python on Windows

Remove Backgrounds from the Specified Slide

There are typically two types of backgrounds in PowerPoint: background colors and background images. Although these backgrounds differ in their setup, the method to clear them is the same - using the BackgroundType property provided by Spire.Presentation for Python. Let's take a closer look at how to remove backgrounds from a PowerPoint slide with it.

Steps to remove background from a specified slide:

  • Create an object for the Presentation class.
  • Load a PowerPoint presentation from the local storage using Presentation.LoadFromFile() method.
  • Get a certain slide with Presentation.Slides[] method.
  • Remove the background by configuring BackgroundType property to none.
  • Save the modified PowerPoint presentation using Presentation.SaveToFile() method, and release the memory.

Here is the code example of removing the background on the fourth slide:

  • Python
from spire.presentation import *

# Create a Presentation document object
presentation = Presentation()
# Read the presentation document from file
presentation.LoadFromFile("imagebackground.pptx")

# Get the fourth slide
slide = presentation.Slides[3]

# Remove the background by setting the background type
slide.SlideBackground.Type = BackgroundType.none

# Save the modified presentation
presentation.SaveToFile("RemoveBackground.pptx", FileFormat.Pptx2010)

# Release resource
presentation.Dispose()

Python: Remove Backgrounds from PowerPoint Slide or Slide Masters

Remove Backgrounds from All Slides

Batch-deleting all slide backgrounds follows nearly the same steps as deleting a single slide background. The main difference is that you'll need to loop through each slide before setting the background type to ensure no slides are missed.

Steps to remove backgrounds from PowerPoint slides in a batch:

  • Instantiate a Presentation class.
  • Specify the file path to read a PowerPoint presentation using Presentation.LoadFromFile() method.
  • Loop through each slide in the presentation.
  • Remove all backgournds by applying BackgroundType.none property to each slide.
  • Save the updated PowerPoint presentation as a new file with Presentation.SaveToFile() method, and release the resource.

Below is the code example for removing each background from PowerPoint slides:

  • Python
from spire.presentation import *

# Create a Presentation document object
presentation = Presentation()
# Read the presentation document from file
presentation.LoadFromFile("presentation.pptx")

# Loop through each slide
for slide in presentation.Slides:
    # Remove the background image or color by setting the background type
    slide.SlideBackground.Type = BackgroundType.none

# Save the modified presentation
presentation.SaveToFile("RemoveBackground_allSlides.pptx", FileFormat.Pptx2010)

# Release resource
presentation.Dispose()

Python: Remove Backgrounds from PowerPoint Slide or Slide Masters

How to Remove Backgrounds from PowerPoint Slide Masters

If the slide background still exists after using the above method, you may need to remove the slide master's background instead. Unlike individual slides, setting the background of a slide master applies changes across all slides, so removing the slide master background can efficiently clear all backgrounds at once.

Steps to remove backgrounds from PowerPoint slide masters:

  • Create an instance of the Presentation class.
  • Load a presentation from the disk with Presentation.LoadFromFile() method.
  • Retrieve a specified slide master using Presentation.Masters[] method.
  • Access the background of the slide master with Masters.SlideBackground property.
  • Remove the background by setting BackgroundType property to none.
  • Save the newly modified PowerPoint presentation with Presentation.SaveToFile() method.

Note: Since the process of batch-removing slide master backgrounds is almost similar to deleting background from a slide master, this section will show the steps in the code comments rather than listing them separately.

Here is an example of removing the background from the third slide master:

  • Python
from spire.presentation import *


# Create a Presentation object
presentation = Presentation()

# Load the sample file from the disk
presentation.LoadFromFile("presentation.pptx")

# Get the third slide master
master = presentation.Masters[2]

# Access the background of the slide master
SlideBackground = master.SlideBackground

# Clear the background by setting the slide master background style to none
master.SlideBackground.Type = BackgroundType.none

# Loop through each slide master
#for master in presentation.Masters:
    # Set the background type to none to remove it
    #master.SlideBackground.Type = BackgroundType.none

# Save the result presentation
presentation.SaveToFile("remove_background.pptx", FileFormat.Pptx2013)

# Release resources
presentation.Dispose()

Python: Remove Backgrounds from PowerPoint Slide or Slide Masters

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

When preparing multiple PowerPoint presentations with similar themes, copying slides helps to maintain consistency in terms of design, layout and content. This ensures that all presentations have a uniform appearance, which can enhance the aesthetics of your document. In this article, you will learn how to copy or clone slides in PowerPoint presentations in Python using Spire.Presentation for Python.

Install Spire.Presentation for Python

This scenario requires Spire.Presentation for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.

pip install Spire.Presentation

If you are unsure how to install, please refer to this tutorial: How to Install Spire.Presentation for Python on Windows

Copy Slides Within the Same Presentation with Python

You can clone a slide either at a specified location or at the end of a PowerPoint presentation through the Presentation.Slides.Insert(Index: int, slide: ISlide) or Presentation.Slides.AppendBySlide(slide: ISlide) methods. The following are the detailed steps.

  • Create a Presentation instance.
  • Load a PowerPoint presentation using Presentation.LoadFromFile() method.
  • Get a specified slide using Prenstion.Slides[] property.
  • Clone the slide to the end of the same presentation using Presentation.Slides.AppendBySlide() method.
  • Clone the slide to a specific position within the same presentation using Presentation.Slides.Insert() method.
  • Save the result file using Presentation.SaveToFile() method.
  • Python
from spire.presentation.common import *
from spire.presentation import *

inputFile ="Input1.pptx"
outputFile ="CloneSlidesWithinTheSame.pptx"

# Create a Presentation instance
ppt = Presentation()

#Load a PowerPoint presentation
ppt.LoadFromFile(inputFile)

# Get the first slide in the presentation
slide = ppt.Slides[0]

# Clone the slide to the end of the presentation
ppt.Slides.AppendBySlide(slide)

# Clone the slide to the third position within the presentation
ppt.Slides.Insert(2, slide)

# Save the result file 
ppt.SaveToFile(outputFile, FileFormat.Pptx2016)
ppt.Dispose()

Python: Copy Slides in PowerPoint Presentations

Copy Slides to Another Presentation with Python

Spire.Presentation for Python also allows you to load two PowerPoint files and then clone the slides from one presentation to another presentation. The following are the detailed steps.

  • Create a Presentation instance.
  • Load two PowerPoint presentations using Presentation.LoadFromFile() method.
  • Get two slides in the first presentation using Prenstion.Slides[] property.
  • Clone the first slide to a specific position in the second presentation using Presentation.Slides.Insert() method.
  • Clone the second slide to the end of the second presentation using Presentation.Slides.AppendBySlide() method.
  • Save the result file using Presentation.SaveToFile() method.
  • Python
from spire.presentation.common import *
from spire.presentation import *

inputFile_1 = "Input1.pptx"
inputFile_2 = "Input2.pptx"
outputFile ="CloneSlidesToAnother.pptx"

# Load the first PowerPoint presentation
sourcePPT = Presentation()
sourcePPT.LoadFromFile(inputFile_1)

# Load the second PowerPoint presentation
destPPT = Presentation()
destPPT.LoadFromFile(inputFile_2)

# Get two slides in the first presentation
slide1 =sourcePPT.Slides[1]
slide2 =sourcePPT.Slides[2]

# Clone slide1 to the second position in the second presentation
destPPT.Slides.Insert(1, slide1)

# Clone slide2 to the end of the second presentation
destPPT.Slides.AppendBySlide(slide2)

# Save the second presentation
destPPT.SaveToFile(outputFile, FileFormat.Pptx2016)
destPPT.Dispose()

Python: Copy Slides in PowerPoint Presentations

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Rearranging slides in a PowerPoint presentation is a simple but essential skill. Whether you need to change the order of your points, group related slides together, or move a slide to a different location, the ability to efficiently reorganize your slides can help you create a more coherent and impactful presentation.

In this article, you will learn how to rearrange slides in a PowerPoint document in Python using Spire.Presentation for Python.

Install Spire.Presentation for Python

This scenario requires Spire.Presentation for Python and plum-dispatch v1.7.4. They can be easily installed in your system through the following pip command.

pip install Spire.Presentation

If you are unsure how to install, please refer to this tutorial: How to Install Spire.Presentation for Python on Windows

Rearrange Slides in a PowerPoint Document in Python

To reorder the slides in PowerPoint, two Presentation objects were created - one for loading the original document, and one for creating a new document. By copying the slides from the original document to the new one in the desired sequence, the slide order could be easily rearranged.

The following are the steps to rearrange slides in a PowerPoint document using Python.

  • Create a Presentation object.
  • Load a PowerPoint document using Presentation.LoadFromFile() method.
  • Specify the slide order within a list.
  • Create another Presentation object for creating a new presentation.
  • Add the slides from the original document to the new presentation in the specified order using Presentation.Slides.AppendBySlide() method.
  • Save the new presentation to a PPTX file using Presentation.SaveToFile() method.
  • Python
from spire.presentation.common import *
from spire.presentation import *

# Create a Presentation object
presentation = Presentation()

# Load a PowerPoint file
presentation.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.pptx")

# Specify the new slide order within a list
newSlideOrder = [4,2,1,3]

# Create another Presentation object
new_presentation =  Presentation()

# Remove the default slide
new_presentation.Slides.RemoveAt(0)

# Iterate through the list
for i in range(len(newSlideOrder)):

    # Add the slides from the original PowerPoint file to the new PowerPoint document in the new order
    new_presentation.Slides.AppendBySlide(presentation.Slides[newSlideOrder[i] - 1])

# Save the new presentation to file
new_presentation.SaveToFile("output/NewOrder.pptx", FileFormat.Pptx2019)

# Dispose resources
presentation.Dispose()
new_presentation.Dispose()

Python: Rearrange Slides in a PowerPoint Document

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Slide Master in PowerPoint presentations is a powerful feature that lies at the heart of designing consistent and professional-looking slideshows. It's essentially a blueprint or a template that controls the overall design and layout of the slides, allowing users to establish uniformity across presentations without having to manually format each slide individually. In this article, we will explore how to harness the power of Spire.Presentation for Python to create, modify, and apply slide masters in PowerPoint presentations within Python programs.

Install Spire.Presentation for Python

This scenario requires Spire.Presentation for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.

pip install Spire.Presentation

If you are unsure how to install, please refer to: How to Install Spire.Presentation for Python on Windows

Create and Apply Slide Masters in PowerPoint Presentations

Every PowerPoint presentation in PowerPoint, regardless of whether it is newly created or not, will have at least one slide master. Developers can modify the default master or create new ones and apply them to slides with Spire.Presentation for Python to achieve a consistent style and content layout across the presentation.

The detailed steps for creating new slide masters and applying them to the slides in a presentation file are as follows:

  • Create an object of Presentation class and load a PowerPoint presentation using Presentation.LoadFromFile() method.
  • Create slide masters using Presentation.Masters.AppendSlide() method.
  • Use the methods under IMasterSlide class to set the backgrounds, customize color schemes, insert images, shapes, and text, etc.
  • Apply the slide masters to specific slides through ISlide.Layout property.
  • Save the presentation using Presentation.SaveToFile() method.
  • Python
from spire.presentation.common import *
from spire.presentation import *

# Create an instance of Presentation class
pres = Presentation()

# Load a Presentation file
pres.LoadFromFile("Sample.pptx")

# Add a cover slide master and a body slide master
master1 = pres.Masters.AppendSlide(pres.Masters.get_Item(0))
coverMaster = pres.Masters.get_Item(master1)
master2 = pres.Masters.AppendSlide(pres.Masters.get_Item(0))
bodyMaster = pres.Masters.get_Item(master2)

# Set background images for the two slide masters
pic1 = "Background1.jpg"
pic2 = "Background2.jpg"

rect = RectangleF.FromLTRB (0, 0, pres.SlideSize.Size.Width, pres.SlideSize.Size.Height)
coverMaster.SlideBackground.Fill.FillType = FillFormatType.Picture
image1 = coverMaster.Shapes.AppendEmbedImageByPath (ShapeType.Rectangle, pic1, rect)
coverMaster.SlideBackground.Fill.PictureFill.Picture.EmbedImage = image1.PictureFill.Picture.EmbedImage

bodyMaster.SlideBackground.Fill.FillType = FillFormatType.Picture
image2 = bodyMaster.Shapes.AppendEmbedImageByPath (ShapeType.Rectangle, pic2, rect)
bodyMaster.SlideBackground.Fill.PictureFill.Picture.EmbedImage = image2.PictureFill.Picture.EmbedImage

# Insert a logo to the body slide master
logo = "Logo.png"
bodyMaster.Shapes.AppendEmbedImageByPath(ShapeType.Rectangle, logo, RectangleF.FromLTRB(pres.SlideSize.Size.Width - 110, 10, pres.SlideSize.Size.Width - 10, 110))

# Insert text to the body slide master
shape = bodyMaster.Shapes.AppendShape(ShapeType.Rectangle, RectangleF.FromLTRB(pres.SlideSize.Size.Width - 210, 110, pres.SlideSize.Size.Width - 10, 150))
shape.Fill.FillType = FillFormatType.none
shape.Line.FillType = FillFormatType.none
shape.TextFrame.Text = "Spire.Presentation"

# Set the color scheme for the two slide masters
coverMaster.Theme.ColorScheme.Accent1.Color = Color.get_Red()
coverMaster.Theme.ColorScheme.Accent2.Color = Color.get_Blue()

bodyMaster.Theme.ColorScheme.Accent1.Color = Color.get_Brown()
coverMaster.Theme.ColorScheme.Accent2.Color = Color.get_Green()

# Apply the first master with layout to the first slide
pres.Slides.get_Item(0).Layout = coverMaster.Layouts.GetByType(SlideLayoutType.Title)

# Apply the second master with layout to other slides
for i in range(1, pres.Slides.Count):
    pres.Slides.get_Item(i).Layout = bodyMaster.Layouts.GetByType(SlideLayoutType.TitleAndObject)

# Save the document
pres.SaveToFile("output/CreateAndApplySlideMaster.pptx", FileFormat.Pptx2016)
pres.Dispose()

Python: Create, Modify, and Copy Slide Master in PowerPoint Presentations

Modify Slide Masters in PowerPoint Presentations

A presentation can have multiple slide masters, which can be applied to different slides to achieve a unified style application and modification for different types of slides.

The Presentation.Masters.get_Item() method in Spire.Presentation for Python allows developers to retrieve the specified slide master in the presentation by index and modify the master. The following step-by-step example demonstrates how to retrieve a slide master and modify its background, color scheme, and embedded images:

  • Create an object of Presentation class and load a PowerPoint presentation using Presentation.LoadFromFile() method.
  • Get a slide master through Presentation.Masters property.
  • Use the methods under IMasterSlide class to change the background, set the color scheme, delete and insert text and images, etc.
  • Save the presentation using Presentation.SaveToFile() method.
  • Python
from spire.presentation.common import *
from spire.presentation import *

# Create an object of Presentation
pres = Presentation()

# Load a PowerPoint presentation
pres.LoadFromFile("output/CreateAndApplySlideMaster.pptx")

# Get the third slide master
master = pres.Masters[2]

# Change the background
master.SlideBackground.Type = BackgroundType.Custom
master.SlideBackground.Fill.FillType = FillFormatType.Solid
master.SlideBackground.Fill.SolidColor.Color = Color.get_LightBlue()

# Change the color sheme
master.Theme.ColorScheme.Accent1.Color = Color.get_Red()
master.Theme.ColorScheme.Accent2.Color = Color.get_Green()

# Remove the pictures in the slide master
pictures = [shape for shape in master.Shapes if isinstance(shape, SlidePicture)]
for picture in pictures:
    master.Shapes.Remove(picture)

# Change the text in the slide master
texts = [shape for shape in master.Shapes if isinstance(shape, IAutoShape)]
for text in texts:
    if len(text.TextFrame.Text) != 0:
        text.TextFrame.Text = "Spire.Presentation for Python"

# Save the presentation
pres.SaveToFile("output/ModifySlideMaster.pptx", FileFormat.Pptx2016)
pres.Dispose()

Python: Create, Modify, and Copy Slide Master in PowerPoint Presentations

Copy Slide Masters Between PowerPoint Presentations

Applying the slide style of a presentation to another presentation can be achieved by copying the slide master between presentations and applying the master style to the specified slides. The following are the steps to copy the slide master between presentations and apply it to the specified slides:

  • Create two objects of Presentation class and load two presentation documents using Presentation.LoadFromFile() method.
  • Get the slide master of the second presentation using Presentation.Masters.get_Item() method.
  • Add the slide master to the first presentation using Presentation.Masters.AppendSlide() method.
  • Apply the slide master to the slides in the second presentation through ISlide.Layout property.
  • Save the first presentation using Presentation.SaveToFile() method.
  • Python
from spire.presentation import *
from spire.presentation.common import *

# Create two objects of Presentation
pres1 = Presentation()
pres2 = Presentation()

# Load two PowerPoint documents
pres1.LoadFromFile("Sample.pptx")
pres2.LoadFromFile("Template.pptx")

# Get the slide master of the second presentation
master = pres2.Masters.get_Item(0)

# Add the slide master to the first presentation
index = pres1.Masters.AppendSlide(master)

# Apply the slide master to the first presentation
pres1.Slides.get_Item(0).Layout = pres1.Masters.get_Item(index).Layouts.GetByType(SlideLayoutType.Title)
for i in range(1, pres1.Slides.Count):
    pres1.Slides.get_Item(i).Layout = pres1.Masters.get_Item(index).Layouts.GetByType(SlideLayoutType.TitleAndObject)

# Save the first presentation
pres1.SaveToFile("output/CopySlideMaster.pptx", FileFormat.Pptx2013)
pres1.Dispose()
pres2.Dispose()

Python: Create, Modify, and Copy Slide Master in PowerPoint Presentations

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Slide titles play a crucial role in PowerPoint presentations because they can assist the audience in quickly grasping the topics or key points of each slide. When working with PowerPoint documents, users often encounter the need to update or extract slide titles for various purposes. For example, they may need to modify titles to reflect new content or extract titles to perform tasks such as summarizing or analyzing presentation content. Knowing how to programmatically update or extract slide titles can greatly save time and effort, particularly when dealing with extensive presentations. In this article, we will demonstrate how to update and extract slide titles in PowerPoint PPTX or PPT documents in Python using Spire.Presentation for Python.

Install Spire.Presentation for Python

This scenario requires Spire.Presentation for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.

pip install Spire.Presentation

If you are unsure how to install, please refer to this tutorial: How to Install Spire.Presentation for Python on Windows

Update Slide Titles in PowerPoint in Python

The title of a slide can be updated using the ISlide.Title property. The detailed steps are as follows.

  • Create a Presentation instance.
  • Load a PowerPoint PPTX or PPT document using Presentation.LoadFromFile() method.
  • Get a specific slide of the document using Presentation.Slides[index] property.
  • Update the title of the slide using ISlide.Title property.
  • Save the result document using Presentation.SaveToFile() method.
  • Python
from spire.presentation.common import *
from spire.presentation import *

# Create a Presentation object
ppt = Presentation()
# Load a PowerPoint document
ppt.LoadFromFile("Water Of Life.pptx")

# Get the second slide
slide = ppt.Slides[1]

# Update the title of the second slide
slide.Title = "Updated Title"

# Save the result document
ppt.SaveToFile("UpdateSlideTitle.pptx", FileFormat.Pptx2016)
ppt.Dispose()

Python: Update or Extract Slide Titles in PowerPoint

Extract All Slide Titles from PowerPoint in Python

To extract all slide titles from a PowerPoint document, you first need to iterate through all slides in the document and all shapes on each slide. Then identify shapes with placeholder types like Title, CenteredTitle, or Subtitle. After that retrieve the text content from the identified shapes using the IAutoShape.TextFrame.Text property. The detailed steps are as follows.

  • Create a Presentation instance.
  • Load a PowerPoint PPTX or PPT document using Presentation.LoadFromFile() method.
  • Create a list to store the extracted titles.
  • Iterate through all slides in the document.
  • For each slide, iterate through all shapes on it.
  • Identify shapes with placeholder types such as Title, CenteredTitle, or Subtitle.
  • Typecast the identified shapes to IAutoShape object.
  • Retrieve the text content of the identified shapes using the IAutoShape.TextFrame.Text property and append them to the list.
  • Save the content of the list to a text file.
  • Python
from spire.presentation.common import *
from spire.presentation import *

# Load a PowerPoint document
ppt = Presentation()
ppt.LoadFromFile("Water of Life.pptx")

# Create a list to store the extracted slide titles
titles = []

# Iterate through all slides in the document
for slide in ppt.Slides:
    # Iterate through all shapes on each slide
    for shape in slide.Shapes:
        # Find the shapes with placeholder types such as Title, CenteredTitle, or Subtitle
        if shape.Placeholder is not None and shape.Placeholder.Type in [PlaceholderType.Title, PlaceholderType.CenteredTitle, PlaceholderType.Subtitle]:
            # Typecast the shape to IautoShape object
            auto_shape = shape if isinstance(shape, IAutoShape) else None
            if auto_shape is not None:
                # Add the text of the shape to the titles list
                titles.append(auto_shape.TextFrame.Text)

# Save the extracted slide titles to a text file
with open("AllTitles.txt", "w") as file:
    file.write("Extracted titles:\n")
    file.write("\n".join(titles))

ppt.Dispose()

Python: Update or Extract Slide Titles in PowerPoint

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Python: Merge PowerPoint Presentations

2024-03-13 00:52:16 Written by Koohji

Working with multiple PowerPoint presentations at the same time can be a daunting task, often resulting in a less-than-ideal presentation experience. However, there is a solution that can streamline this process and ensure seamless transitions throughout the presentation. By combining multiple PowerPoint files into a single cohesive presentation, presenters can eliminate the need to repeatedly open different files, saving time and effort. While manually copying slides can be arduous and time-consuming, Python offers a swift and efficient solution. This article is going to show how to leverage Spire.Presentation for Python to merge PowerPoint presentations effortlessly through Python programs.

Install Spire.PDF for Python

This scenario requires Spire.Presentation for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.

pip install Spire.Presentation

If you are unsure how to install, please refer to: How to Install Spire.Presentation for Python on Windows

Merging PowerPoint Presentations and Retain Their Designs

Merging PowerPoint presentations can be accomplished by reading slides from one presentation and adding them to another presentation. During the process of adding to the target presentation, developers can use Presentation.Slides.AppendBySlide(ISlide) method to add slides and retain the original design of the slides.

The detailed steps are as follows:

  • Create two instances of Presentation class.
  • Load two PowerPoint presentations using Presentation.LoadFromFile() method.
  • Iterate through each slide in the second presentation and add them to the first presentation while keeping their design using Presentation.Slides.AppendBySlide() method.
  • Save the first presentation using Presentation.SaveToFile() method.
  • Python
from spire.presentation import *
from spire.presentation.common import *

# Create two instances of Presentation class
pres1 = Presentation()
pres2 = Presentation()

# Load two presentation files
pres1.LoadFromFile("Sample1.pptx")
pres2.LoadFromFile("Sample2.pptx")

# Iterate through the slides of the second presentation
for slide in pres2.Slides:
    # Add each slides to the first presentation and keep the original design
    pres1.Slides.AppendBySlide(slide)

# Save the first presentation
pres1.SaveToFile("output/MergePresentations.pptx", FileFormat.Pptx2016)
pres1.Dispose()
pres2.Dispose()

Python: Merge PowerPoint Presentations

Merging PowerPoint Presentations with Consistent Design

Developers can also use Presentation.Slides.AppendByMaster(slide Islide, master IMasterSlide) method to insert slides into the target presentation and change the design of the slides to the design of the target presentation. This allows for merging presentations and ensuring a consistent design.

The detailed stops are as follows:

  • Create two instances of Presentation class.
  • Load two PowerPoint presentations using Presentation.LoadFromFile() method.
  • Iterate through each slide in the second presentation and add them to the first presentation while changing their design to the design of the first presentation using Presentation.Slides.AppendByMaster() method.
  • Save the first presentation using Presentation.SaveToFile() method.
  • Python
from spire.presentation import *
from spire.presentation.common import *

# Create two instances of Presentation class
pres1 = Presentation()
pres2 = Presentation()

# Load two presentation files
pres1.LoadFromFile("Sample1.pptx")
pres2.LoadFromFile("Sample2.pptx")

# Iterate through each slide in the second presentation
for slide in pres2.Slides:
    # Add each slide to the first presentation
    pres1.Slides.AppendByMaster(slide, pres1.Masters[0])

# Save the first presentation
pres1.SaveToFile("output/MergePresentationsDesign.pptx", FileFormat.Pptx2016)
pres1.Dispose()
pres2.Dispose()

Python: Merge PowerPoint Presentations

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Page 1 of 2
page 1