Table borders in PowerPoint refer to the visible lines or outlines that surround the cells within a table. These borders provide a visual separation between cells and help define the boundaries of the table. By setting or modifying table borders, you can customize the appearance of tables in your PowerPoint presentations. In this article, we will guide you on how to set and remove table borders in PowerPoint 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

Set Table Borders in PowerPoint in Python

Spire.Presentation for Python provides the ITable.SetTableBorder() method, which allows you to set borders for a table in PowerPoint. The detailed steps are as follows.

  • Create an object of the Presentation class.
  • Get the first slide of the presentation using Presentation.Slides[] property.
  • Add a table to the slide using ISlide.Shapes.AppendTable() method.
  • Add borders to the table and set the border type, width, and color using ITable.SetTableBorder() method.
  • Save the result presentation using Presentation.SaveToFile() method.
  • Python
from spire.presentation.common import *
from spire.presentation import *

# Create a Presentation object
presentation = Presentation()
# Get  the first slide of the presentation
slide = presentation.Slides[0]

# Specify the number and size of rows and columns in table
widths = [100, 100, 100, 100, 100]
heights = [20, 20]

# Add a table to the first slide
table = slide.Shapes.AppendTable(100, 100, widths, heights)

# Add borders to the table and set the border type, width, and color
table.SetTableBorder(TableBorderType.All, 1, Color.get_Blue())

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

Python: Set or Remove Table Borders in PowerPoint

Remove Table Borders in PowerPoint in Python

To remove borders from a table, you need to iterate through the cells in the table and then remove the borders from each cell. The detailed steps are as follows.

  • Create an object of the Presentation class.
  • Load a PowerPoint presentation using Presentation.LoadFromFile() method.
  • Get a specific slide of the presentation using Presentation.Slides[] property.
  • Get the table on the slide.
  • Iterate through the rows in the table and the cells in each row.
  • Remove the borders from each cell by setting the fill type of the top, bottom, left and right borders of the cell as none.
  • Save the result presentation using Presentation.SaveToFile() method.
  • Python
from spire.presentation.common import *
from spire.presentation import *

# Create a PowerPoint presentation
presentation = Presentation()
# Load a PowerPoint presentation
presentation.LoadFromFile("SetBorders.pptx")

# Get the first slide
slide = presentation.Slides[0]
# Get the table on the slide
table = slide.Shapes[0] if isinstance(slide.Shapes[0], ITable) else None
table = (ITable)(table)

# Iterate through the rows and cells in the table
for row in table.TableRows:
    for cell in row:
        # Remove borders from each cell by setting the fill type of the top, bottom, left and right borders of the cell as none
        cell.BorderTop.FillType = FillFormatType.none
        cell.BorderBottom.FillType = FillFormatType.none
        cell.BorderLeft.FillType = FillFormatType.none
        cell.BorderRight.FillType = FillFormatType.none

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

Python: Set or Remove Table Borders 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.

Margins in a PDF document refer to the blank spaces surrounding the content on each page. They act as a buffer zone between the text or images and the edges of the page. Changing the margins of a PDF document can be a useful task when you want to adjust the layout, accommodate annotations or comments, or prepare the document for printing or presentation.

This article introduces how to modify the margins of a PDF document using the Spire.PDF for Python library. You will discover techniques to both increase and reduce the margins of your PDFs, enabling you to customize the layout according to your specific requirements.

Install Spire.PDF for Python

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

pip install Spire.PDF

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

Increase the Margins of a PDF Document in Python

In Spire.PDF for Python, there isn't a direct method to modify the margins of an existing PDF document. However, you can increase the margins by creating a new PDF document with a page size equal to the original document's page size plus the increased margin values. Then, copy and paste (draw) each page of the original document into the appropriate place on the new document page.

The following are the steps to increase the margins of a PDF document using Python.

  1. Create a PdfDocument object called "originalPdf" and load the original PDF document.
  2. Create another PdfDocument object called "newPdf" for creating a new PDF document.
  3. Specify the desired increase values for the top, bottom, left, and right margins.
  4. Calculate the new page size by adding the margin increase values to the original page dimensions.
  5. Create a template based on the original PDF page using PdfPageBase.CreateTemplate() method.
  6. Add a new page to the "newPdf" document with the calculated page size using PdfDocument.Pages.Add() method.
  7. Draw the template onto the new page at the appropriate location to using PdfTemplate.Draw() method.
  8. Repeat steps 5-7 for each page in the original PDF document.
  9. Save the "newPdf" object to a PDF file.
  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a PdfDocument object
originalPdf = PdfDocument()

# Load a PDF file
originalPdf.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.pdf")

# Get the first page
"firstPage = originalPdf.Pages.get_Item(0)

# Create another PdfDocument object for creating new document
newPdf = PdfDocument()

# Set the increase values of the margins
marginsToAdd = newPdf.PageSettings.Margins
marginsToAdd.Top = 40
marginsToAdd.Bottom = 40
marginsToAdd.Left = 40
marginsToAdd.Right = 40

# Calculate the new page size
sizeF = SizeF(firstPage.Size.Width + marginsToAdd.Left + marginsToAdd.Right, firstPage.Size.Height + marginsToAdd.Top + marginsToAdd.Bottom)

# Iterate through the pages in the original document
for i in range(originalPdf.Pages.Count):

    # Create a template based on a specific page
    pdfTemplate = originalPdf.Pages.get_Item(i).CreateTemplate()"

    # Add a page to the new PDF
    page = newPdf.Pages.Add(sizeF)

    # Draw template on the page
    pdfTemplate.Draw(page, 0.0, 0.0)

# Save the new document
newPdf.SaveToFile("Output/IncreaseMargins.pdf", FileFormat.PDF)

# Dispose resources
originalPdf.Dispose()
newPdf.Dispose()

Python: Change the Margins of a PDF Document

Reduce the Margins of a PDF Document in Python

Similarly, you can reduce the margins by creating a new PDF document with a page size equal to the page size of the original document minus the margin value to be reduced. Then, copy and paste (draw) each page of the original document into the appropriate place on the new document page.

To reduce the margins of a PDF document using Python, follow these steps:

  1. Create a PdfDocument object called "originalPdf" and load the original PDF document.
  2. Create another PdfDocument object called "newPdf" for creating a new PDF document.
  3. Specify the desired reduction values for the top, bottom, left, and right margins.
  4. Calculate the new page size by subtracting the margin value to be reduced from the original page size.
  5. Create a template based on the original PDF page using PdfPageBase.CreateTemplate() method.
  6. Add a new page to the "newPdf" document with the calculated page size using PdfDocument.Pages.Add() method.
  7. Draw the template onto the new page at the appropriate location using PdfTemplate.Draw() method.
  8. Repeat steps 5-7 for each page in the original PDF document.
  9. Save the "newPdf" object to a PDF file.
  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a PdfDocument object
originalPdf = PdfDocument()

# Load a PDF file
originalPdf.LoadFromFile(""C:\\Users\\Administrator\\Desktop\\Input.pdf"")

# Get the first page
firstPage = originalPdf.Pages.get_Item(0)

# Create another PdfDocument object
newPdf = PdfDocument()

# Set the reduction value of the margins
topToReduce = 20.0
bottomToReduce = 20.0
leftToReduce = 20.0
rightToReduce = 20.0

# Calculate the new page size
sizeF = SizeF(firstPage.Size.Width - leftToReduce - rightToReduce, firstPage.Size.Height - topToReduce - bottomToReduce)

# Iterate through the pages in the original document
for i in range(originalPdf.Pages.Count):

    # Create a template based on a specific page
    pdfTemplate = originalPdf.Pages.get_Item(i).CreateTemplate()

    # Add a page to the new PDF
    page = newPdf.Pages.Add(sizeF, PdfMargins(0.0))

    # Draw template on the page
    pdfTemplate.Draw(page, -leftToReduce, -topToReduce)

# Save the new document
newPdf.SaveToFile(""Output/ReduceMargins.pdf"", FileFormat.PDF)

# Dispose resources
originalPdf.Dispose()
newPdf.Dispose()

Python: Change the Margins of a PDF 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.

Paragraph spacing and line spacing are crucial formatting options in Microsoft Word that greatly influence the visual presentation and readability of your documents. Paragraph spacing determines the vertical space between paragraphs, creating a distinct separation between each paragraph. Line spacing, on the other hand, controls the vertical distance between lines within a paragraph, directly impacting the density and readability of the text. By appropriately setting paragraph spacing and line spacing, you can easily create visually appealing and easy-to-read documents. In this article, we will explain how to set paragraph spacing and line spacing in Word documents in Python using Spire.Doc for Python.

Install Spire.Doc for Python

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

pip install Spire.Doc

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

Set Paragraph Spacing in Word in Python

Spire.Doc for Python provides the Paragraph.Format.BeforeSpacing and Paragraph.Format.AfterSpacing properties to adjust the spacing before and after a paragraph. The detailed steps are as follows.

  • Create an object of the Document class.
  • Add a section to the document using Document.AddSection() method.
  • Add two paragraphs to the section using Section.AddParagraph() methods.
  • Set the spacing before and after the paragraphs using Paragraph.Format.BeforeSpacing and Paragraph.Format.AfterSpacing properties.
  • Save the result document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create an object of the Document class
document = Document()
# Add a section to the document
section = document.AddSection()

# Add two paragraphs to the section
para1 = section.AddParagraph()
para1.Format.HorizontalAlignment = HorizontalAlignment.Center
textRange1 = para1.AppendText("Spire.Doc for Python")
textRange1.CharacterFormat.TextColor = Color.get_Blue()
textRange1.CharacterFormat.FontName = "Calibri"
textRange1.CharacterFormat.FontSize = 15

para2 = section.AddParagraph()
textRange2 = para2.AppendText("Spire.Doc for Python is a professional Word Python API specifically designed for developers to create, read, write, convert, and compare Word documents with fast and high-quality performance.")
textRange2.CharacterFormat.FontName = "Calibri"
textRange2.CharacterFormat.FontSize = 12

# Set the spacing after the first paragraph
para1.Format.AfterAutoSpacing = False
para1.Format.AfterSpacing = 10

# Set the spacing before and after the second paragraph
para2.Format.BeforeAutoSpacing = False
para2.Format.BeforeSpacing = 10
para2.Format.AfterAutoSpacing = False
para2.Format.AfterSpacing = 10

# Save the result file
document.SaveToFile("SetParagraphSpacing.docx", FileFormat.Docx2013)
document.Close()

Python: Set Paragraph Spacing and Line Spacing in Word

Set Line Spacing in Word in Python

To set the pacing between lines in a paragraph, you can use the Paragraph.Format.LineSpacing property. The detailed steps are as follows.

  • Create an object of the Document class.
  • Add a section to the document using Document.AddSection() method.
  • Add a paragraph to the section using Section.AddParagraph() methods.
  • Set the spacing between lines in the paragraph using Paragraph.Format.LineSpacing property.
  • Save the result document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create an object of the Document class
document = Document()
# Add a section
section = document.AddSection()

# Add a paragraph to the section
para = section.AddParagraph()
textRange = para.AppendText("Spire.Doc for Python is a proven reliable MS Word API for Python which enables to perform many Word document processing tasks. Spire.Doc for Python supports Word 97-2003 /2007/2010/2013/2016/2019 and it has the ability to convert them to commonly used file formats like XML, RTF, TXT, XPS, EPUB, EMF, HTML and vice versa. Furthermore, it supports to convert Word Doc/Docx to PDF using Python, Word to SVG, and Word to PostScript in high quality.")
textRange.CharacterFormat.FontName = "Calibri"
textRange.CharacterFormat.FontSize = 12

# Set line spacing rule
para.Format.LineSpacingRule = LineSpacingRule.Multiple
# Set line spacing value (The line spacing rule "Multiple" with value 18 sets the line spacing to "1.5 lines", value 12 sets the line spacing to "Single")
para.Format.LineSpacing = 18

# Save the result file
document.SaveToFile("SetLineSpacing.docx", FileFormat.Docx2013)
document.Close()

Python: Set Paragraph Spacing and Line Spacing in Word

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: Convert TXT to PDF

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

PDF is an ideal file format for sharing and archiving. If you are working with text files, you may find it beneficial to convert them to PDF files for enhanced portability, security and format preservation. In this article, you will learn how to convert TXT files to PDF in Python using Spire.PDF for Python.

Install Spire.PDF for Python

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

pip install Spire.PDF

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

Convert TXT to PDF with Python

Spire.PDF for Python allows to convert text files to PDF by reading the text content from the input TXT file, and then drawing it onto the pages of a PDF document. Some of the core classes and methods used are listed below:

  • PdfDocument class: Represents a PDF document model.
  • PdfTextWidget class: Represents the text area with the ability to span several pages.
  • File.ReadAllText() method: Reads the text in the text file into a string object.
  • PdfDocument.Pages.Add() method: Adds a page to a PDF document.
  • PdfTextWidget.Draw() method: Draws the text widget at a specified location on the page.

The following are the detailed steps to convert TXT to PDF in Python:

  • Read text from the TXT file using File.ReadAllText() method.
  • Create a PdfDocument instance and add a page to the PDF file.
  • Create a PDF font and brush objects.
  • Set the text format and layout.
  • Create a PdfTextWidget object to hold the text content.
  • Draw the text widget at a specified location on the PDF page using PdfTextWidget.Draw() method.
  • Save the PDF file using PdfDocument.SaveToFile() method.
  • Python
from spire.pdf.common import *
from spire.pdf import *

def ReadFromTxt(fname: str) -> str:
    with open(fname, 'r') as f:
        text = f.read()
    return text

inputFile = "input.txt"
outputFile = "TextToPdf.pdf"

# Get text from the txt file
text = ReadFromTxt(inputFile)

# Create a PdfDocument instance
pdf = PdfDocument()

# Add a page
page = pdf.Pages.Add()

# Create a PDF font and PDF brush
font = PdfFont(PdfFontFamily.TimesRoman, 11.0)
brush = PdfBrushes.get_Black()

# Set the text alignment and line spacing
strformat = PdfStringFormat()
strformat.LineSpacing = 10.0
strformat.Alignment = PdfTextAlignment.Justify

# Set the text layout 
textLayout = PdfTextLayout()
textLayout.Break = PdfLayoutBreakType.FitPage
textLayout.Layout = PdfLayoutType.Paginate

# Create a PdfTextWidget instance to hold the text content
textWidget = PdfTextWidget(text, font, brush)

# Set the text format
textWidget.StringFormat = strformat

# Draw the text at the specified location on the page
bounds = RectangleF(PointF(0.0, 20.0), page.Canvas.ClientSize)
textWidget.Draw(page, bounds, textLayout)

# Save the result file
pdf.SaveToFile(outputFile, FileFormat.PDF)
pdf.Close()

Python: Convert TXT to PDF

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: Insert Rows and Columns in Excel

2024-03-08 08:33:42 Written by Koohji

If you have additional pieces of information to include in your spreadsheet, inserting rows or columns can provide room for these new fields. In addition,
adding blank rows or columns between data sets can also help to effectively separate different categories of information, making them easier to read and analyze. This article will demonstrate how to insert rows and columns in Excel in Python using Spire.XLS for Python.

Install Spire.XLS for Python

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

pip install Spire.XLS

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

Insert a Row and a Column in Excel in Python

Spire.XLS for Python provides the Worksheet.InsertRow(rowIndex: int) and Worksheet.InsertColumn(columnIndex: int) methods for inserting a blank row and a blank column in an Excel worksheet. The following are the detailed steps:

  • Create a Workbook instance.
  • Load a sample Excel file using Workbook.LoadFromFile() method.
  • Get a specified worksheet using Workbook.Worksheets[sheetIndex] property.
  • Insert a row into the worksheet using Worksheet.InsertRow(rowIndex: int) method.
  • Insert a column into the worksheet using Worksheet.InsertColumn(columnIndex: int) method.
  • Save the result file using Workbook.SaveToFile() method.
  • Python
from spire.xls import *
from spire.xls.common import *

inputFile = "input.xlsx"
outputFile = "InsertRowAndColumn.xlsx"

# Create a Workbook instance
workbook = Workbook()

# Load an Excel document 
workbook.LoadFromFile(inputFile)

# Get a specified worksheet
worksheet = workbook.Worksheets[0]

# Insert a blank row as the 5th row in the worksheet 
worksheet.InsertRow(5)

# Insert a blank column as the 4th column in the worksheet 
worksheet.InsertColumn(4)

# Save the result file
workbook.SaveToFile(outputFile, ExcelVersion.Version2016)
workbook.Dispose()

Python: Insert Rows and Columns in Excel

Insert Multiple Rows and Columns in Excel in Python

To insert multiple rows and columns into a worksheet, you can use the Worksheet.InsertRow(rowIndex: int, rowCount: int) and Worksheet.InsertColumn(columnIndex: int, columnCount: int) methods. The following are detailed steps.

  • Create a Workbook instance.
  • Load a sample Excel file using Workbook.LoadFromFile() method.
  • Get a specified worksheet using Workbook.Worksheets[sheetIndex] property.
  • Insert multiple rows into the worksheet using Worksheet.InsertRow(rowIndex: int, rowCount: int) method.
  • Insert multiple columns into the worksheet using Worksheet.InsertColumn(columnIndex: int, columnCount: int) method.
  • Save the result file using Workbook.SaveToFile() method.
  • Python
from spire.xls import *
from spire.xls.common import *

inputFile = "input.xlsx"
outputFile = "InsertRowsAndColumns.xlsx"

# Create a Workbook instance
workbook = Workbook()

# Load an Excel document 
workbook.LoadFromFile(inputFile)

# Get a specified worksheet
worksheet = workbook.Worksheets[0]

# Insert three blank rows into the worksheet
worksheet.InsertRow(5, 3)

#Insert two blank columns into the worksheet
worksheet.InsertColumn(4, 2)

# Save the result file
workbook.SaveToFile(outputFile, ExcelVersion.Version2016)
workbook.Dispose()

Python: Insert Rows and Columns in Excel

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.

Incorporating audio and videos in slides has become a common practice for creating interactive and dynamic PowerPoint presentations, which helps the presenter in sharing information, engaging the audience, and delivering impactful messages. However, as content requirements change, there arises a need to replace or update these multimedia elements. This article will show how to use Spire.Presentation for Python to replace audio and videos in PowerPoint presentations for content updating needs such as updating outdated videos, enhancing audio quality, or simply swapping in new content.

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

Replace a Video in a PowerPoint Presentation with Python

With Spire.Presentation for Python, developers can find the video shapes in slides and replace the video data through IVideo.EmbeddedVideoData property. It is important to note that, after replacing the video, the preview of the video should also be updated with the IVideo.PictureFill.Picture property. The detailed steps are as follows:

  • Create an object of Presentation class and load a PowerPoint presentation file using Presentation.LoadFromFile() method.
  • Get the collection of the videos embedded in the presentation through Presentation.Videos property.
  • Get the slide that contains the video to be replaced through Presentation.Slides[] property.
  • Iterate through the shapes in the slide and determine if a shape is an instance of IVideo class. If it is, append the new video to the video collection using VideoCollection.AppendByStream() method and replace the original video with the new video through IVideo.EmbeddedVideoData property.
  • Embed a new image to the presentation using Presentation.Images.AppendStream() method and set it as the preview of the video through IVideo.PictureFill.Picture.EmbedImage property. You can also set an online image as the preview through IVideo.PictureFill.Picture.Url property.
  • Save the presentation using Presentation.SaveToFile() method.
  • Python
from spire.presentation import *
from spire.presentation.common import *

# Create an object of the Presentation class
pres = Presentation()

# Load a PowerPoint presentation
pres.LoadFromFile("Sample.pptx")

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

# Get the videos in the presentation
videos = pres.Videos

# Iterate through the shapes on the slide
for shape in slide.Shapes:
    # Check if the shape is a video
    if isinstance(shape, IVideo):
        video = shape if isinstance(shape, IVideo) else None
        # Append a new video to the video collection
        videoData = videos.AppendByStream(Stream("Ocean2.mp4"))
        # Replace the video in the shape with the new video
        video.EmbeddedVideoData = videoData
        # Embed a picture in the presentation
        imageData = pres.Images.AppendStream(Stream("Ocean2.png"))
        # Set the new picture as the preview of the video
        video.PictureFill.Picture.EmbedImage = imageData

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

Python: Replace Videos and Audio in PowerPoint Presentations

Replace an Audio in a PowerPoint Presentation with Python

Similarly, developers can also use Spire.Presentation for Python to find specific audio in a presentation slide and replace the audio data. The detailed steps are as follows:

  • Create an object of Presentation class and load a PowerPoint presentation file using Presentation.LoadFromFile() method.
  • Get the collection of the audio embedded in the presentation through Presentation.WavAudios property.
  • Get the slide that contains audio to be replaced through Presentation.Slides[] property.
  • Iterate through each shape in the slide and check if a shape is an instance of IAudio class. If it is, append the new audio to the audio collection using WavAudioCollection.Append() method and replace the original audio with the new audio through IAudio.Data property.
  • Save the presentation using Presentation.SaveToFile() method.
  • Python
from spire.presentation import *
from spire.presentation.common import *

# Create an object of the Presentation class
pres = Presentation()

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

# Get the audio collection from the presentation
audios = pres.WavAudios

# Get the slide that contains the audio
slide = pres.Slides[0]

# Iterate through each shape in the slide
for shape in slide.Shapes:
    # Check if the shape is an audio shape
    if isinstance(shape, IAudio):
        audio = shape if isinstance(shape, IAudio) else None
        # Load an audio file
        stream = Stream("Wave.wav")
        # Replace the audio in the shape
        audioData = audios.Append(stream)
        audio.Data = audioData

# Save the presentation
pres.SaveToFile("output/ReplaceAudio.pptx", FileFormat.Pptx2016)
pres.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.

Directly extracting text has emerged as a crucial method for obtaining textual information from information-dense PowerPoint presentations. By utilizing Python programs, users can conveniently and quickly access the content within slides, enabling efficient collection of information and further data processing. This article shows how to use Spire.Presentation for Python to extract text from PowerPoint presentations, including text in slides, speaker notes, and comments.

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 commands.

pip install Spire.Presentation

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

Extract Text from Presentation Slides with Python

The text within PowerPoint presentation slides is placed within shapes. Therefore, developers can extract the text from the presentation by accessing all the shapes within each slide and extracting the text contained within them. The detailed steps are as follows:

  • Create an object of Presentation class and load PowerPoint presentation using Presentation.LoadFromFile() method.
  • Iterate through the slides in the presentation and then iterate through the shapes in each slide.
  • Check if a shape is an IAutoShape instance. If it is, get the paragraphs in the shape through IAutoShape.TextFrame.Paragraphs property and then get the text in the paragraphs through Paragraph.Text property.
  • Write the slide text to a text file.
  • Python
from spire.presentation import *
from spire.presentation.common import *

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

# Load a PowerPoint presentation
pres.LoadFromFile("Sample.pptx")

text = []
# Loop through each slide
for slide in pres.Slides:
    # Loop through each shape
    for shape in slide.Shapes:
        # Check if the shape is an IAutoShape instance
        if isinstance(shape, IAutoShape):
            # Extract the text from the shape
            for paragraph in (shape if isinstance(shape, IAutoShape) else None).TextFrame.Paragraphs:
                text.append(paragraph.Text)

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

Python: Extract Text from PowerPoint Presentations

Extract Text from Speaker Notes with Python

Speaker notes are additional information that provides guidance to the presenter and are not visible to the audience. The text in speaker notes of each slide is stored in the notes slide and developers can extract the text through NotesSlide.NotesTextFrame.Text property. The detailed steps for extracting text in speaker notes are as follows:

  • Create an object of Presentation class and load PowerPoint presentation using Presentation.LoadFromFile() method.
  • Iterate through each slide.
  • Get the note slide through ISlide.NotesSlide property and retrieve the text through NotesSlide.NotesTextFrame.Text property.
  • Write the speaker note text to a text file.
  • Python
from spire.presentation import *
from spire.presentation.common import *

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

# Load a PowerPoint presentation
pres.LoadFromFile("Sample.pptx")

list = []
# Iterate through each slide
for slide in pres.Slides:
    # Get the notes slide
    notesSlide = slide.NotesSlide
    # Get the notes
    notes = notesSlide.NotesTextFrame.Text
    list.append(notes)

# Write the notes to a text file
f = open("output/SpeakerNoteText.txt", "w", encoding="utf-8")
for note in list:
    f.write(note)
    f.write("\n")
f.close()
pres.Dispose()

Python: Extract Text from PowerPoint Presentations

Extract Text from Presentation Comments with Python

With Spire.Presentation for Python, developers can also extract the text from comments in PowerPoint presentations by getting comments from slides with ISlide.Comments property and retrieving text from comments with Comment.Text property. The detailed steps are as follows:

  • Create an object of Presentation class and load PowerPoint presentation using Presentation.LoadFromFile() method.
  • Iterate through each slide and get the comment from each slide through ISlide.Comments property.
  • Iterate through each comment and retrieve the text from each comment through Comment.Text property.
  • Write the comment text to a text file.
  • Python
from spire.presentation import *
from spire.presentation.common import *

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

# Load a PowerPoint presentation
pres.LoadFromFile("Sample.pptx")

list = []
# Iterate through all slides
for slide in pres.Slides:
    # Get all comments from the slide
    comments = slide.Comments
    # Iterate through the comments
    for comment in comments:
        # Get the comment text
        commentText = comment.Text
        list.append(commentText)

# Write the comments to a text file
f = open("output/CommentText.txt", "w", encoding="utf-8")
for i in range(len(list)):
    f.write(list[i] + "\n")
f.close()
pres.Dispose()

Python: Extract Text from 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.

Moving and deleting worksheets in Excel are essential operations that allow you to organize and manage your workbook efficiently. Moving worksheets enables you to adjust the order of worksheets to match your specific needs or bring related information together. While deleting worksheets helps you eliminate unwanted or redundant sheets, creating a cleaner and more organized workspace. In this article, we will demonstrate how to move and delete worksheets in Excel in Python using Spire.XLS for Python.

Install Spire.XLS for Python

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

pip install Spire.XLS

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

Move a Worksheet in Excel in Python

You can easily move a worksheet in an Excel file to another position by using the Worksheet.MoveWorksheet() method provided by Spire.XLS for Python. The detailed steps are as follows.

  • Create an object of the Workbook class.
  • Load an Excel file using the Workbook.LoadFromFile() method.
  • Get a specific worksheet in the file using the Workbook.Worksheet[] property.
  • Move the worksheet to another position in the file using the Worksheet.MoveWorksheet() method.
  • Save the result file using the Workbook.SaveToFile() method.
  • Python
from spire.xls import *
from spire.xls.common import *

# Create an object of the Workbook class
workbook = Workbook()
# Load a sample Excel file
workbook.LoadFromFile("Sample.xlsx")

# Get a specific worksheet in the file by its index
sheet = workbook.Worksheets[0]
# Or get a specific worksheet in the file by its name
# sheet = workbook.Worksheets["Sheet1"]

# Move the worksheet to the 3rd position in the file
sheet.MoveWorksheet(2)

# Save the result file
workbook.SaveToFile("MoveWorksheet.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Python: Move or Delete Worksheets in Excel

Delete a Worksheet in Excel in Python

You can delete a specific worksheet from an Excel file by using the Workbook.Worksheets.RemoveAt() or Workbook.Worksheets.Remove() method provided by Spire.XLS for Python. The detailed steps are as follows.

  • Create an object of the Workbook class.
  • Load an Excel file using the Workbook.LoadFromFile() method.
  • Remove a specific worksheet from the file using the Workbook.Worksheets.RemoveAt() or Workbook.Worksheets.Remove() method.
  • Save the result file using the Workbook.SaveToFile() method.
  • Python
from spire.xls import *
from spire.xls.common import *

# Create an object of the Workbook class
workbook = Workbook()
# Load a sample Excel file
workbook.LoadFromFile("Sample.xlsx")

# Remove a specific worksheet in the file by its index
workbook.Worksheets.RemoveAt(0)

# Or get a specific worksheet in the file by its name and then remove it
# worksheet = workbook.Worksheets["Sheet1"]
# workbook.Worksheets.Remove(worksheet)

# Save the result file
workbook.SaveToFile("DeleteWorksheet.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Python: Move or Delete Worksheets in Excel

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.

Comparing two Word documents for differences is a crucial task when reviewing changes, ensuring accuracy, and collaborating on content. This process allows you to identify additions, deletions, and modifications made between different document iterations. By comparing versions, you can efficiently track alterations, verify updates, and maintain document integrity. In this article, you will learn how to compare two versions of a Word document in Python using the Spire.Doc for Python library.

Install Spire.Doc for Python

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

pip install Spire.Doc

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

Compare Two Versions of a Word Document in Python

MS Word also offers a "Compare" feature that allows you to directly compare two versions of a document. This feature generates a new document that highlights the differences between the two versions.

To achieve similar results using Spire.Doc for Python, load the original and revised versions into two separate Document objects. Then, use the Compare() method to compare the revised version against the original. Finally, save the comparative document, which highlights the alterations, using the SaveToFile() method.

The steps to compare two version of a Word document using Python are as follows.

  • Load the first document (original version) while initializing the Document object.
  • Load the second document (revised version) while initializing the Document object.
  • Call Compare() method of the first Document object to compare the revised version against the original version.
  • Save the comparison results in a new Word document.
  • Python
from spire.doc import *
from spire.doc.common import *

# Load the first document while initializing the Document object
firstDoc = Document("C:\\Users\\Administrator\\Desktop\\Original.docx")

# Load the second document while initializing the Document object
secondDoc = Document("C:\\Users\\Administrator\\Desktop\\Revised.docx")

# Compare two documents
firstDoc.Compare(secondDoc, "E-ICEBLUE")

# Save the comparison results in a new document
firstDoc.SaveToFile("Output/Differences.docx", FileFormat.Docx2016)

# Dispose resources
firstDoc.Dispose()
secondDoc.Dispose()

Python: Compare Two Versions of a Word Document

Compare Two Versions of a Word Document While Ignoring Formatting in Python

Comparing two versions of a Word document while ignoring formatting can be useful when you want to focus solely on the textual changes and disregard any formatting modifications.

To customize the comparison options in Spire.Doc for Python, use the CompareOptions class. If you want to exclude formatting from the comparison process, you can set the IgnoreFormatting property of the CompareOptions object to True. When you call the Compare() method, simply pass the CompareOptions object as an argument to achieve the desired comparison behavior.

The following are the steps to compare two versions of a Word document while ignoring formatting using Python.

  • Load the first document (original version) while initializing the Document object.
  • Load the second document (revised version) while initializing the Document object.
  • Create a CompareOptions object and set its IgnoreFormatting property to True.
  • Call Compare() method of the first Document object, passing the CompareOptions object as a parameter, to compare the revision against the original while ignoring formatting.
  • Save the comparison results in a new Word document.
  • Python
from spire.doc import *
from spire.doc.common import *

# Load the first document while initializing the Document object
firstDoc = Document("C:\\Users\\Administrator\\Desktop\\Original.docx")

# Load the second document while initializing the Document object
secondDoc = Document("C:\\Users\\Administrator\\Desktop\\Revised.docx")

# Set compare option to ignore formatting changes
compareOptions = CompareOptions()
compareOptions.IgnoreFormatting = True

# Compare the two Word documents with options
firstDoc.Compare(secondDoc, "E-ICEBLUE", compareOptions)

# Save the comparison results in a new document
firstDoc.SaveToFile("Output/DifferencesWithoutFormattingChanges.docx", FileFormat.Docx2016)

# Dispose resources
firstDoc.Dispose()
secondDoc.Dispose()

Python: Compare Two Versions of a Word 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.

page 14