Speaker notes in PowerPoint play a crucial role in enhancing the presenter's delivery and ensuring a seamless presentation experience. They can be added to individual slides to provide valuable guidance, reminders, and supplementary information for the presenter. Unlike the content displayed on the slides, speaker notes are typically not visible to the audience during the actual presentation. In this article, we'll explain how to add, read or delete speaker notes in a PowerPoint presentation 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

Add Speaker Notes to PowerPoint in Python

Spire.Presentation for Python provides the ISlide.AddNotesSlides() method to add notes to a PowerPoint slide. The detailed steps are as follows.

  • Create a Presentation object.
  • Load a PowerPoint presentation using Presentation.LoadFromFile() method.
  • Get the slide that you want to add notes to using Presentation.Slides[index] property.
  • Add a notes slide to the slide using ISlide.AddNotesSlides() method.
  • Create TextParagraph objects and set text for the paragraphs using TextParagraph.Text property, then add the paragraphs to the notes slide using NotesSlide.NotesTextFrame.Paragraphs.Append() method.
  • Save the resulting presentation using Presentation.SaveToFile() method.
  • Python
from spire.presentation.common import *
from spire.presentation import *

# Create a Presentation object
ppt = Presentation()
# Load a PowerPoint presentation
ppt.LoadFromFile("Sample.pptx")

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

# Add a notes slide to the slide
notesSlide = slide.AddNotesSlide()

# Add 4 paragraphs to the notes slide
paragraph = TextParagraph()
paragraph.Text = "Tips for making effective presentations:"
notesSlide.NotesTextFrame.Paragraphs.Append(paragraph)

paragraph = TextParagraph()
paragraph.Text = "Use the slide master feature to create a consistent and simple design template."
notesSlide.NotesTextFrame.Paragraphs.Append(paragraph)

paragraph = TextParagraph()
paragraph.Text = "Simplify and limit the number of words on each screen."
notesSlide.NotesTextFrame.Paragraphs.Append(paragraph)

paragraph = TextParagraph()
paragraph.Text = "Use contrasting colors for text and background."
notesSlide.NotesTextFrame.Paragraphs.Append(paragraph)

# Set bullet type and style for specific paragraphs
for i in range(1, notesSlide.NotesTextFrame.Paragraphs.Count):
    notesSlide.NotesTextFrame.Paragraphs[i].BulletType = TextBulletType.Numbered
    notesSlide.NotesTextFrame.Paragraphs[i].BulletStyle = NumberedBulletStyle.BulletArabicPeriod

# Save the resulting presentation
ppt.SaveToFile("AddSpeakerNotes.pptx", FileFormat.Pptx2016)
ppt.Dispose()

Python: Add, Read or Delete Speaker Notes in PowerPoint

Read Speaker Notes in PowerPoint in Python

To read the text content of the notes, you can use the NotesSlide.NotesTextFrame.Text property. The detailed steps are as follows.

  • Create a Presentation object.
  • Load a PowerPoint presentation using Presentation.LoadFromFile() method.
  • Get the slide that you want to read notes from using Presentation.Slides[index] property.
  • Get the notes slide of the slide using ISlide.NotesSlide property.
  • Get the text content of the notes slide using NotesSlide.NotesTextFrame.Text property.
  • Write the text content into a text file.
  • Python
from spire.presentation.common import *
from spire.presentation import *

# Create a Presentation object
ppt = Presentation()
# Load a PowerPoint presentation
ppt.LoadFromFile("AddSpeakerNotes.pptx")

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

# Get the notes slide of the slide
notesSlide = slide.NotesSlide

# Get the text content of the notes slide
notes = notesSlide.NotesTextFrame.Text

# Write the text content to a text file
with open("Notes.txt", 'w') as file:
    file.write(notes)

ppt.Dispose()

Python: Add, Read or Delete Speaker Notes in PowerPoint

Delete Speaker Notes from PowerPoint in Python

You can delete a specific paragraph of note or delete all the notes from a slide using the NotesSlide.NotesTextFrame.Paragraphs.RemoveAt(index) or NotesSlide.NotesTextFrame.Paragraphs.Clear() method. The detailed steps are as follows.

  • Create a Presentation object.
  • Load a PowerPoint presentation using Presentation.LoadFromFile() method.
  • Get the slide that you want to delete notes from using Presentation.Slides[index] property.
  • Get the notes slide of the slide using ISlide.NotesSlide property.
  • Delete a specific paragraph of note or delete all the notes from the notes slide using the NotesSlide.NotesTextFrame.Paragraphs.RemoveAt(index) or NotesSlide.NotesTextFrame.Paragraphs.Clear() method.
  • Save the resulting presentation using Presentation.SaveToFile() method.
  • Python
from spire.presentation.common import *
from spire.presentation import *

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

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

# Get the notes slide of the slide
notesSlide = slide.NotesSlide

# Remove a specific paragraph of note from the notes slide
# notesSlide.NotesTextFrame.Paragraphs.RemoveAt(1)

# Remove all the notes from the notes slide
notesSlide.NotesTextFrame.Paragraphs.Clear()

# Save the resulting presentation
presentation.SaveToFile("DeleteSpeakerNotes.pptx", FileFormat.Pptx2013)
presentation.Dispose()

Python: Add, Read or Delete Speaker Notes 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 Word Documents

2023-11-07 00:57:30 Written by Koohji

Dealing with a large number of Word documents can be very challenging. Whether it's editing or reviewing a large number of documents, there's a lot of time wasted on opening and closing documents. What's more, sharing and receiving a large number of separate Word documents can be annoying, as it may require a lot of repeated sending and receiving operations by both the sharer and the receiver. Therefore, in order to enhance efficiency and save time, it is advisable to merge related Word documents into a single file. From this article, you will know how to use Spire.Doc for Python to easily merge Word documents through Python programs.

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 this tutorial: How to Install Spire.Doc for Python on Windows

Merge Word Documents by Inserting Files with Python

The method Document.insertTextFromFile() is used to insert other Word documents to the current one, and the inserted content will start from a new page. The detailed steps for merging Word documents by inserting are as follows:

  • Create an object of Document class and load a Word document using Document.LoadFromFile() method.
  • Insert the content from another document to it using Document.InsertTextFromFile() method.
  • Save the document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create an object of Document class and load a Word document
doc = Document()
doc.LoadFromFile("Sample1.docx")

# Insert the content from another Word document to this one
doc.InsertTextFromFile("Sample2.docx", FileFormat.Auto)

# Save the document
doc.SaveToFile("output/InsertDocuments.docx")
doc.Close()

Python: Merge Word Documents

Merge Word Documents by Cloning Contents with Python

Merging Word documents can also be achieved by cloning contents from one Word document to another. This method maintains the formatting of the original document, and content cloned from another document continues at the end of the current document without starting a new Page. The detailed steps are as follows:

  • Create two objects of Document class and load two Word documents using Document.LoadFromFile() method.
  • Get the last section of the destination document using Document.Sections.get_Item() method.
  • Loop through the sections in the document to be cloned and then loop through the child objects of the sections.
  • Get a section child object using Section.Body.ChildObjects.get_Item() method.
  • Add the child object to the last section of the destination document using Section.Body.ChildObjects.Add() method.
  • Save the result document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create two objects of Document class and load two Word documents
doc1 = Document()
doc1.LoadFromFile("Sample1.docx")
doc2 = Document()
doc2.LoadFromFile("Sample2.docx")

# Get the last section of the first document
lastSection = doc1.Sections.get_Item(doc1.Sections.Count - 1)

# Loop through the sections in the second document
for i in range(doc2.Sections.Count):
    section = doc2.Sections.get_Item(i)
    # Loop through the child objects in the sections
    for j in range(section.Body.ChildObjects.Count):
        obj = section.Body.ChildObjects.get_Item(j)
        # Add the child objects from the second document to the last section of the first document
        lastSection.Body.ChildObjects.Add(obj.Clone())

# Save the result document
doc1.SaveToFile("output/MergeByCloning.docx")
doc1.Close()
doc2.Close()

Python: Merge Word Documents

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.

The ability to set a password for a PDF document or remove the password from an encrypted PDF document is invaluable for securing sensitive information while maintaining the flexibility and convenience of working with PDF files. By setting up passwords for PDF documents, individuals can control access to their files, preventing unauthorized viewing, editing, or copying. Conversely, unprotecting a PDF document can make the document accessible or editable again. In this article, you will learn how to password-protect PDF documents as well as how to remove passwords from encrypt PDF documents 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

Protect PDF with Password in Python

There are two types of passwords that can be used for security purposes: the "open password" and the "permission password". An open password, also known as a user password, is used to restrict unauthorized access to a PDF file. A permission password, also referred to as a master password or owner password, allows you to set various restrictions on what others can do with the PDF file. If a PDF file is secured with both types of passwords, it can be opened with either password.

The PdfDocument.Security.Encrypt(String openPassword, String permissionPassword, PdfPermissionsFlags permissions, PdfEncryptionKeySize keySize) method offered by Spire.PDF for Python allows you to protect PDF files with an open password and/or a permission password. The parameter PdfPermessionsFlags is used to specify the user's permission to operate the document.

Here are the steps to password-protect a PDF with Spire.PDF for Python.

  • Create a PdfDocument object.
  • Load a sample PDF file using PdfDocument.LoadFromFile() method.
  • Encrypt the PDF file with an open password and permission password using PdfDocument.Security.Encrypt(String openPassword, String permissionPassword, PdfPermissionsFlags permissions, PdfEncryptionKeySize keySize) method.
  • Save the result file using PdfDocument.SaveToFile() method.
  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a PdfDocument object
doc = PdfDocument()

# Load a sample PDF file
doc.LoadFromFile("C:/Users/Administrator/Desktop/input.pdf")

# Encrypt the PDF file with an open password and a permission password
doc.Security.Encrypt("openPsd", "permissionPsd", PdfPermissionsFlags.FillFields, PdfEncryptionKeySize.Key128Bit)

# Save the result file
doc.SaveToFile("output/Encrypted.pdf", FileFormat.PDF)

Python: Protect or Unprotect PDF Documents

Remove Password from an Encrypted PDF in Python

To remove the password from a PDF file, call the PdfDocument.Security.Encrypt() method and leave the open password and permission password empty. The following are the detailed steps.

  • Create a PdfDocument object.
  • Load an encrypted PDF file using PdfDocument.LoadFromFile(String fileName, String password) method.
  • Decrypt the PDF file by setting the open password and permission password to empty using PdfSecurity.Encrypt(String openPassword, String permissionPassword, PdfPermissionsFlags permissions, PdfEncryptionKeySize keySize, String originalPermissionPassword) method.
  • Save the result file using PdfDocument.SaveToFile() method.
  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a PdfDocument object
doc = PdfDocument()

# Load an encrypted PDF file
doc.LoadFromFile("C:/Users/Administrator/Desktop/Encrypted.pdf", "openPsd")

# Set the open password and permission password as empty 
doc.Security.Encrypt(str(), str(), PdfPermissionsFlags.Default, PdfEncryptionKeySize.Key128Bit, "permissionPsd")

# Save the result file
doc.SaveToFile("output/RemovePassword.pdf", FileFormat.PDF)

Python: Protect or Unprotect PDF Documents

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.

Combine Excel Workbooks or Worksheets into One using Python

Merging Excel files is a common task for data analysts and financial teams working with large datasets. While Microsoft Excel supports manual merging, it becomes inefficient and error-prone when dealing with large volumes of files.

In this step-by-step guide, you will learn how to merge multiple Excel files (.xls and .xlsx) using Python and Spire.XLS for Python library. Whether you're combining workbooks, merging worksheets, or automating bulk Excel file processing, this guide will help you save time and streamline your workflow with practical solutions.

Table of Contents

Why Merge Excel Files with Python?

Using Python to merge Excel files brings several key advantages:

  • Automation: Save time and eliminate repetitive manual work by automating the merging process.
  • No Excel Dependency: Merge files without installing Microsoft Excel—ideal for headless, server-side, or cloud environments.
  • Flexible Merging: Customize merging by selecting specific sheets, ranges, columns, or rows.
  • Scalability: Handle hundreds or even thousands of Excel files with consistent performance.
  • Error Reduction: Reduce manual errors and ensure data accuracy with automated scripts.

Whether you’re consolidating monthly reports or merging large datasets, Python helps streamline the process efficiently.

Getting Started with Spire.XLS for Python

Spire.XLS for Python is a standalone library that allows developers to create, read, edit, and save Excel files without the need for Microsoft Excel installation.

Key Features Include:

  • Supports Multiple Formats: .xls, .xlsx, and more.
  • Worksheet Operations: Copy, rename, delete, and merge worksheets seamlessly across workbooks.
  • Formula & Formatting Preservation: Retain formulas and formatting during editing or merging.
  • Advanced Features: Includes chart creation, conditional formatting, pivot tables, and more.
  • File Conversion: Convert Excel files to PDF, HTML, CSV, and more.

Installation

Run the following pip command in your terminal or command prompt to install Spire.XLS from PyPI:

pip install spire.xls

How to Merge Multiple Excel Files into One Workbook using Python

When working with multiple Excel files, consolidating all worksheets into a single workbook can simplify data management and reporting. This approach preserves each original worksheet separately, making it easy to organize and review data from different sources such as department budgets, regional reports, or monthly summaries.

Steps

To merge multiple Excel files into a single workbook using Python, follow these steps:

  • Loop through the files.
  • Load each Excel file using LoadFromFile().
  • For the first file, assign it as the base workbook.
  • For subsequent files, copy all worksheets into the base workbook using AddCopy().
  • Save the final combined workbook to a new file.

Code Example

import os
from spire.xls import *

# Folder containing Excel files to merge
input_folder = './sample_files'   
# Output file name for the merged workbook       
output_file = 'merged_workbook.xlsx'    

# Initialize merged workbook as None
merged_workbook = None  

# Iterate over all files in the input folder
for filename in os.listdir(input_folder):
    # Process only Excel files with .xls or .xlsx extensions
    if filename.endswith('.xlsx') or filename.endswith('.xls'):
        file_path = os.path.join(input_folder, filename)
        
        # Load the current Excel file into a Workbook object
        source_workbook = Workbook()
        source_workbook.LoadFromFile(file_path)

        if merged_workbook is None:
            # For the first file, assign it as the base merged workbook
            merged_workbook = source_workbook
        else:
            # For subsequent files, copy each worksheet into the merged workbook
            for i in range(source_workbook.Worksheets.Count):
                sheet = source_workbook.Worksheets.get_Item(i)
                merged_workbook.Worksheets.AddCopy(sheet, WorksheetCopyType.CopyAll)

# Save the combined workbook to the specified output file
merged_workbook.SaveToFile(output_file, ExcelVersion.Version2016)

Consolidate Excel Files into One using Python

How to Combine Multiple Excel Worksheets into a Single Worksheet using Python

Merging data from multiple Excel worksheets into one worksheet allows you to aggregate information efficiently, especially when working with data such as sales logs, survey responses, or performance reports.

Steps

To combine worksheet data from multiple Excel files into a single worksheet using Python, follow these steps:

  • Create a new workbook and select its first worksheet as the destination.
  • Loop through the files.
  • Load each Excel file using LoadFromFile().
  • Get the desired worksheet that you want to merge from the current file.
  • Copy the used cell range from the desired worksheet to the destination worksheet, placing data consecutively below the previously copied content.
  • Save the combined data into a new Excel file.

Code Example

import os
from spire.xls import *

# Folder containing Excel files to merge
input_folder = './excel_worksheets'
# Output file name for the merged workbook
output_file = 'merged_into_one_sheet.xlsx'

# Create a new workbook to hold merged data
merged_workbook = Workbook()
# Use the first worksheet in the new workbook as the merge target
merged_sheet = merged_workbook.Worksheets[0]

# Initialize the starting row for copying data
current_row = 1

# Loop through all files in the input folder
for filename in os.listdir(input_folder):
    # Process only Excel files (.xls or .xlsx)
    if filename.endswith('.xlsx') or filename.endswith('.xls'):
        file_path = os.path.join(input_folder, filename)

        # Load the current Excel file
        workbook = Workbook()
        workbook.LoadFromFile(file_path)

        # Get the first worksheet from the current workbook
        sheet = workbook.Worksheets[0]

        # Get the used range from the first worksheet
        source_range = sheet.Range

        # Set the destination range in the merged worksheet starting at current_row
        dest_range = merged_sheet.Range[current_row, 1]

        # Copy data from the used range to the destination range
        source_range.Copy(dest_range)

        # Update current_row to the row after the last copied row to prevent overlap
        current_row += sheet.LastRow

# Save the merged workbook to the specified output file in Excel 2016 format
merged_workbook.SaveToFile(output_file, ExcelVersion.Version2016)

Merge Excel Worksheets into One using Python

Conclusion

When merging multiple Excel files into a single document—whether by appending sheets or combining data row by row—using a Python library like Spire.XLS enables automation and improves accuracy. This approach can help streamline workflows, especially in enterprise scenarios that require handling large datasets without relying on Microsoft Excel.

FAQs: Merge Excel Files with Python

Q1: Can I merge .xls and .xlsx files together?

A1: Yes. Spire.XLS handles both formats without needing conversion.

Q2: Do I need Excel installed on my machine to use Spire.XLS?

A2: No. Spire.XLS is standalone and works without Microsoft Office installed.

Q3: Can I merge only specific sheets from each workbook?

A3: Yes. You can customize your code to merge sheets by name or index. For example:

sheet = source_workbook.Worksheets["Summary"]

Q4: How do I avoid copying header rows multiple times?

A4: Add logic like:

if current_row > 1:
    start_row = 2 # Skip header

else:
    start_row = 1

Q5: Can I keep track of which file each row came from?

A5: Yes. Add a new column in the merged sheet containing the source file name for each row.

Q6: Is there a file size or row limit when using Spire.XLS?

A6: Spire.XLS follows the same row and column limits as Excel: .xlsx supports up to 1,048,576 rows × 16,384 columns, and .xls supports up to 65,536 rows × 256 columns.

Q7: Can I preserve formulas and formatting while merging?

A7: Yes. When merging Excel files, formatting and formulas are preserved.

SmartArt in Microsoft PowerPoint is a valuable tool that allows users to create visually appealing diagrams, charts, and graphics to represent information or concepts. It provides a quick and easy way to transform plain text into visually engaging visuals, making it easier for the audience to understand and remember the information being presented. In this article, we will demonstrate how to create, read and delete SmartArt in a 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

Create SmartArt in PowerPoint in Python

Spire.Presentation for Python provides the ISlide.Shapes.AppendSmartArt() method to add a SmartArt graphic to a specific slide of a PowerPoint presentation. The detailed steps are as follows.

  • Create an object of the Presentation class.
  • Load a PowerPoint presentation using Presentation.LoadFromFile() method.
  • Get a specified slide by its index using Presentation.Slides[index] property.
  • Insert a SmartArt graphic into the specified slide using ISlide.Shapes.AppendSmartArt() method.
  • Set the style and color of the SmartArt using ISmartArt.Style and ISmartArt.ColorStyle properties.
  • Loop through the nodes in the SmartArt and remove all default nodes using ISmartArt.Nodes.RemoveNode() method.
  • Add a node to the SmartArt using ISmartArt.Nodes.AddNode() method.
  • Add two sub-nodes to the node using ISmartArtNode.ChildNodes.AddNode() method.
  • Add two sub-nodes to the first sub-node and the second sub-node respectively using ISmartArtNode.ChildNodes.AddNode() method.
  • Add text to each node and sub-node using ISmartArtNode.TextFrame.Text property, and then set the font size for the text using ISmartArtNode.TextFrame.TextRange.FontHeight property.
  • Save the resulting presentation using Presentation.SaveToFile() method.
  • Python
from spire.presentation.common import *
from spire.presentation import *

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

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

# Add a SmartArt (Organization Chart) to the slide
smartArt = slide.Shapes.AppendSmartArt(200, 60, 500, 430, SmartArtLayoutType.OrganizationChart)

# Set style and color for the SmartArt
smartArt.Style = SmartArtStyleType.ModerateEffect
smartArt.ColorStyle = SmartArtColorType.ColorfulAccentColors5to6

# Remove the default nodes from the SmartArt
list = []
for node in smartArt.Nodes:
    list.append(node)
for subnode in list:
    smartArt.Nodes.RemoveNode(subnode)

# Add a node to the SmartArt
node = smartArt.Nodes.AddNode()

# Add two sub-nodes to the node
subNode1 = node.ChildNodes.AddNode()
subNode2 = node.ChildNodes.AddNode()

# Add two sub-nodes to the first sub-node
subsubNode1 = subNode1.ChildNodes.AddNode()
subsubNode2 = subNode1.ChildNodes.AddNode()
# Add two sub-nodes to the second sub-node
subsubNode3 = subNode2.ChildNodes.AddNode()
subsubNode4 = subNode2.ChildNodes.AddNode()

# Set text and font size for the node and sub-nodes
node.TextFrame.Text = "CEO"
node.TextFrame.TextRange.FontHeight = 14.0
subNode1.TextFrame.Text = "Development Manager"
subNode1.TextFrame.TextRange.FontHeight = 12.0
subNode2.TextFrame.Text = "Quality Assurance Manager"
subNode2.TextFrame.TextRange.FontHeight = 12.0
subsubNode1.TextFrame.Text = "Developer A"
subsubNode1.TextFrame.TextRange.FontHeight = 12.0
subsubNode2.TextFrame.Text = "Developer B"
subsubNode2.TextFrame.TextRange.FontHeight = 12.0
subsubNode3.TextFrame.Text = "Tester A"
subsubNode3.TextFrame.TextRange.FontHeight = 12.0
subsubNode4.TextFrame.Text = "Tester B"
subsubNode4.TextFrame.TextRange.FontHeight = 12.0

# Save the resulting presentation
presentation.SaveToFile("InsertSmartArt.pptx", FileFormat.Pptx2016)
presentation.Dispose()

Python: Create, Read or Delete SmartArt in PowerPoint

Read SmartArt in PowerPoint in Python

To read the text of SmartArt graphics on a PowerPoint slide, you need to find the SmartArt shapes on the slide, then loop through all nodes of each SmartArt shape, and finally retrieve the text of each node through the ISmartArtNode.TextFrame.Text property. 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 using Presentation.Slides[index] property.
  • Create a list to store the extracted text.
  • Loop through all the shapes on the slide.
  • Check if the shapes are of ISmartArt type. If the result is True, loop through all the nodes of each SmartArt shape, then retrieve the text from each node through ISmartArtNode.TextFrame.Text property and append the text to the list.
  • Write the text in the list into a text file.
  • Python
from spire.presentation.common import *
from spire.presentation import *

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

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

# Create a list to store the extracted text
str = []
str.append("Text Extracted from SmartArt:")

# 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 shapes and append the text to the list
        for node in smartArt.Nodes:
            str.append(node.TextFrame.Text)

# Write the text in the list into a text file
with open("ExtractTextFromSmartArt.txt", "w", encoding = "utf-8") as text_file:
    for text in str:
        text_file.write(text + "\n")

presentation.Dispose()

Python: Create, Read or Delete SmartArt in PowerPoint

Delete SmartArt from PowerPoint in Python

To delete SmartArt graphics from a PowerPoint slide, you need to loop through all the shapes on the slide, find the SmartArt shapes and then delete them from the slide using ISlide.Shapes.Remove() method. 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 using Presentation.Slides[index] property.
  • Create a list to store the SmartArt shapes.
  • Loop through all the shapes on the slide.
  • Check if the shapes are of ISmartArt type. If the result is True, append them to the list.
  • Loop through the SmartArt shapes in the list, then remove them from the slide one by one using ISlide.Shapes.Remove() method.
  • Save the resulting presentation using Presentation.SaveToFile() method.
  • Python
from spire.presentation.common import *
from spire.presentation import *

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

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

# Create a list to store the SmartArt shapes
list = []

# Loop through all the shapes on the slide
for shape in slide.Shapes:
    # Find the SmartArt shapes and append them to the list
    if isinstance (shape, ISmartArt):
        list.append(shape)

# Remove the SmartArt from the slide
for smartArt in list:
    slide.Shapes.Remove(smartArt)

# Save the resulting presentation
presentation.SaveToFile("DeleteSmartArt.pptx", FileFormat.Pptx2016)
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.

Pivot tables provide a flexible way to organize, manipulate, and summarize data from different perspectives, enabling users to gain valuable insights and make informed decisions. With pivot tables, you can easily rearrange and summarize data based on various criteria, such as categories, dates, or numerical values. This feature is particularly useful when dealing with complex datasets or when you need to compare and analyze data from different angles. In this article, you will learn how to create or operate pivot tables in an Excel document 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

Create a Pivot Table in Excel in Python

Spire.XLS for Python offers the PivotTable class to work with pivot tables in an Excel document. To create a pivot table based on the data in an existing Excel worksheet, follow the steps below.

  • Create a Workbook object.
  • Load a sample Excel document using Workbook.LoadFromFile() method.
  • Get a specified worksheet through Workbook.Worksheets[index] property.
  • Specify the range of cells on which the pivot table will be created using Worksheet.Range property
  • Create an object of PivotCache using Workbook.PivotCaches.Add() method.
  • Add a pivot table to the worksheet using Worksheet.PivotTables.Add() method.
  • Add fields to rows area.
  • Add fields to values area.
  • Save the result document using Workbook.SaveToFile() method.
  • Python
from spire.xls import *
from spire.xls.common import *

# Create a Workbook object
workbook = Workbook()

# Load a sample Excel document
workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Data.xlsx")

# Get the first worksheet
sheet = workbook.Worksheets[0]

# Select the data source range
cellRange = sheet.Range["C1:F11"]
piVotCache = workbook.PivotCaches.Add(cellRange)

# Add a PivotTable to the worksheet and set the location and cache of it
pivotTable = sheet.PivotTables.Add("Pivot Table", sheet.Range["H1"], piVotCache)

# Add "Region" and "Product" fields to rows area
regionField = pivotTable.PivotFields["Region"]
regionField.Axis = AxisTypes.Row
pivotTable.Options.RowHeaderCaption = "Region"
productField = pivotTable.PivotFields["Product"]
productField.Axis = AxisTypes.Row

# Add "Quantity" and "Amount" fields to values area
pivotTable.DataFields.Add(pivotTable.PivotFields["Quantity"], "SUM of Quantity", SubtotalTypes.Sum)
pivotTable.DataFields.Add(pivotTable.PivotFields["Amount"], "SUM of Amount", SubtotalTypes.Sum)

# Apply a built-in style to the pivot table
pivotTable.BuiltInStyle = PivotBuiltInStyles.PivotStyleMedium11

# Set column width
sheet.SetColumnWidth(8, 16);
sheet.SetColumnWidth(9, 16);
sheet.SetColumnWidth(10, 16);

# Save the document
workbook.SaveToFile("output/PivotTable.xlsx", ExcelVersion.Version2016)

Python: Create or Operate Pivot Tables in Excel

Sort Pivot Table by Column Values in Python

A specific field can be accessed through the PivotTable.PivotFields[index] property, and then you can set its sort type using the PivotField.SortType property. The following are the steps to sort pivot table by the values of a specific field.

  • Create a Workbook object.
  • Load an Excel document using Workbook.LoadFromFile() method.
  • Get a specific worksheet through Workbook.Worksheets[index] property.
  • Get a specific pivot table from the worksheet through Worksheet.PivotTables[index] property.
  • Get a specific field through PivotTable.PivotFields[fieldName] property.
  • Sort data in the field through PivotField.SortType property.
  • Save the workbook to a different file using Workbook.SaveToFile() method.
  • Python
from spire.xls import *
from spire.xls.common import *

# Create a Workbook object
workbook = Workbook()

# Load an Excel document
workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\PivotTable.xlsx");

# Get the first worksheet
sheet = workbook.Worksheets[0]

# Get the specified pivot table
pivotTable = sheet.PivotTables[0]

# Get the specified field
idField = pivotTable.PivotFields["Order ID"]

# Sort data in the column of "Order ID" field
idField.SortType = PivotFieldSortType.Descending

# Save the document
workbook.SaveToFile("output/SortData.xlsx", ExcelVersion.Version2016)

Python: Create or Operate Pivot Tables in Excel

Expand or Collapse Rows in Pivot Table in Python

To collapse the details under a certain pivot field, use PivotField.HideItemDetail(string itemValue, bool isHiddenDetail) method and set the second parameter to true; to show the details, set the second parameter to false. The detailed steps are as follows.

  • Create a Workbook object.
  • Load an Excel document using Workbook.LoadFromFile() method.
  • Get a specific worksheet through Workbook.Worksheets[index] property.
  • Get a specific pivot table from the worksheet through Worksheet.PivotTables[index] property.
  • Get a specific field through PivotTable.PivotFields[fieldName] property.
  • Collapse or expand rows of the field using PivotField.HideItemDetail(string itemValue, bool isHiddenDetail) method.
  • Save the workbook to a different file using Workbook.SaveToFile() method.
  • Python
from spire.xls import *
from spire.xls.common import *

# Create a Workbook object
workbook = Workbook()

# Load a sample Excel document
workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\PivotTable.xlsx");

# Get the first worksheet
sheet = workbook.Worksheets[0]

# Get the specified pivot table
pivotTable = sheet.PivotTables[0]

# Get the specified field
regoinField = pivotTable.PivotFields["Region"]

# Hide details under the selected item of the region
regoinField.HideItemDetail("West", True)
regoinField.HideItemDetail("East", True)

# Save the document
workbook.SaveToFile("output/CollapseRows.xlsx", ExcelVersion.Version2016)

Python: Create or Operate Pivot Tables 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.

Comments are invaluable tools for collaboration and feedback in Word documents, allowing users to provide insights, suggestions, clarification, and discussions. Whether the goal is to share ideas, respond to existing comments, or remove outdated feedback, mastering the efficient handling of Word document comments can significantly enhance document workflow. This article aims to show how to add, delete, or reply to comments in Word documents using Spire.Doc for Python in Python programs.

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 this tutorial: How to Install Spire.Doc for Python on Windows

Add Comments to a Paragraph in Word Documents using Python

Spire.Doc for Python provides the Paragraph.AppendComment() method to add a comment to a specified paragraph. And the range of text corresponding to the comment needs to be controlled using the comment start marks and end marks. The detailed steps to add comments on paragraphs are as follows:

  • Create an object of Document class and load a Word document using Document.LoadFromFile() method.
  • Get the first section using Document.Sections.get_Item() method.
  • Get the first paragraph in the section using Section.Paragraphs.get_Item() method.
  • Add a comment to the paragraph using Paragraph.AppendComment() method.
  • Set the author the comment through Comment.Format.Author property.
  • Create a comment start mark and an end mark and set them as the start and end marks of the created comment though CommentMark.CommentId property.
  • Insert the comment start mark and end mark at the beginning and end of the paragraph respectively using Paragraph.ChildObjects.Insert() method.
  • Save the document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create an object of Document class and load a Word document
doc = Document()
doc.LoadFromFile("Sample.docx")

# Get the first section
section = doc.Sections.get_Item(0)

# Get the forth paragraph
paragraph = section.Paragraphs.get_Item(4)

# Add a comment to the paragraph
comment = paragraph.AppendComment("Lack of detail on the history of the currency.")

# Set the author of the comment
comment.Format.Author = "Joe Butler"

# Create a comment start mark and an end mark and set them as the start and end marks of the created comment
commentStart = CommentMark(doc, CommentMarkType.CommentStart)
commentEnd = CommentMark(doc, CommentMarkType.CommentEnd)
commentStart.CommentId = comment.Format.CommentId
commentEnd.CommentId = comment.Format.CommentId

# Insert the comment start mark and end mark at the beginning and end of the paragraph respectively
paragraph.ChildObjects.Insert(0, commentStart)
paragraph.ChildObjects.Add(commentEnd)

# Save the document
doc.SaveToFile("output/CommentOnParagraph.docx")
doc.Close()

Python: Add, Delete, or Reply to Comments in Word Documents

Add Comments to Text in Word Documents using Python

Spire.Doc for Python also supports finding specified text and adding comments to it. The detailed steps are as follows:

  • Create an object of Document class and load a Word document using Document.LoadFromFile() method.
  • Find the text to comment on using Document.FindString() method.
  • Create an object of Comment class, set the comment content through Comment.Body.AddParagraph().Text property, and set the author of the comment through Comment.Format.Author property.
  • Get the text as one text range using TextSelection.GetAsOneRange() method and get the paragraph the text belongs to through TextRange.OwnerParagraph property.
  • Insert the comment after the found text using Paragraph.ChildObjects.Insert() method.
  • Create a comment start mark and an end mark and set them as the start and end marks of the created comment though CommentMark.CommentId property.
  • Insert the comment start mark and end mark before and after found text respectively using Paragraph.ChildObjects.Insert() method.
  • Save the document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create an object of Document class and load a Word document
doc = Document()
doc.LoadFromFile("Sample.docx")

# Find the text to comment on
text = doc.FindString("medium of exchange", True, True)

# Create a comment and set the content and author of the comment
comment = Comment(doc)
comment.Body.AddParagraph().Text = "Fiat currency is the only legal means of payment within a country or region."
comment.Format.Author = "Linda Taylor"

# Get the found text as a text range and get the paragraph it belongs to
range = text.GetAsOneRange()
paragraph =  range.OwnerParagraph

# Add the comment to the paragraph
paragraph.ChildObjects.Insert(paragraph.ChildObjects.IndexOf(range) + 1, comment)

# Create a comment start mark and an end mark and set them as the start and end marks of the created comment
commentStart = CommentMark(doc, CommentMarkType.CommentStart)
commentEnd = CommentMark(doc, CommentMarkType.CommentEnd)
commentStart.CommentId = comment.Format.CommentId
commentEnd.CommentId = comment.Format.CommentId

# Insert the created comment start and end tags before and after the found text respectively
paragraph.ChildObjects.Insert(paragraph.ChildObjects.IndexOf(range), commentStart)
paragraph.ChildObjects.Insert(paragraph.ChildObjects.IndexOf(range) + 1, commentEnd)

# Save the document
doc.SaveToFile ("output/CommentOnText.docx")
doc.Close()

Python: Add, Delete, or Reply to Comments in Word Documents

Remove Comments from Word Documents using Python

Spire.Doc for Python provides the Document.Comments.RemoveAt() method that can be used to remove a specified comment and the Document.Clear() method that can remove all comments. The detailed steps for removing comments are as follows:

  • Create an object of Document class and load a Word document using Document.LoadFromFile() method.
  • Delete a specific comment using Document.Comments.RemoveAt() method or delete all the comments using Document.Comments.Clear() method.
  • Save the document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create an object of Document class and load a Word document
doc = Document()
doc.LoadFromFile("Sample1.docx")

# Remove the second comment
doc.Comments.RemoveAt(1)

# Remove all comments
#doc.Comments.Clear()

# Save the document
doc.SaveToFile("output/RemoveComments.docx")
doc.Close()

Python: Add, Delete, or Reply to Comments in Word Documents

Reply to Comments in Word Documents using Python

Spire.Doc for Python allows users to reply to a comment by setting a comment as a reply to another comment using Comment.ReplyToComment(Comment) method. The detailed steps are as follows:

  • Create an object of Document class and load a Word document using Document.LoadFromFile() method.
  • Get a comment using Document.Comments.get_Item() method.
  • Create a comment and set its content and author through Comment.Body.AddParagraph().Text property and Comment.Format.Author property.
  • Set the created comment as a reply to the obtained comment using Comment.ReplyToComment() method.
  • Save the document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create an object of Document class and load a Word document
doc = Document()
doc.LoadFromFile("output/CommentOnParagraph.docx")

# Get a comment
comment = doc.Comments.get_Item(0)

# Create a reply comment and set the content and author of it
reply = Comment(doc)
reply.Body.AddParagraph().Text = "We will give more details about the history of the currency."
reply.Format.Author = "Moris Peter"

# Set the created comment as a reply to obtained comment
comment.ReplyToComment(reply)

# Save the document
doc.SaveToFile("output/ReplyToComments.docx")
doc.Close()

Python: Add, Delete, or Reply to Comments in Word Documents

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.

Textboxes are versatile tools in Microsoft Word, allowing you to insert and position text or other elements anywhere on a page, giving you the power to create eye-catching flyers, brochures, or reports. Whether you're looking to emphasize a particular section of text, place captions near images, or simply add a decorative touch, the capacity to manipulate textboxes offers a practical and aesthetic advantage in document design. In this article, you will learn how to add or remove textboxes in a Word document 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 command.

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

Add a Textbox to a Word Document in Python

Spire.Doc for Python provides the Paragraph.AppendTextBox() method to insert a textbox in a specified paragraph. The content and formatting of the textbox can be set through the properties under the TextBox object. The following are the detailed steps.

  • Create a Document object.
  • Load a Word document using Document.LoadFromFile() method.
  • Get the first section and add a paragraph to the section using Section.AddParagraph() method.
  • Add a text box to the paragraph using Paragraph.AppendTextBox() method.
  • Get the format of the textbox using TextBox.Format property, and then set the textbox's wrapping type, position, border color and fill color using the properties of TextBoxFormat Class.
  • Add a paragraph to the textbox using TextBox.Body.AddParagraph() method.
  • Add an image to the paragraph using Paragraph.AppendPicture() method.
  • Add text to the textbox using Paragraph.AppendText() method
  • Save the document to a different file using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a Word document
document.LoadFromFile("C:/Users/Administrator/Desktop/input3.docx")

# Insert a textbox and set its wrapping style
textBox = document.Sections[0].Paragraphs[0].AppendTextBox(135, 300)
textBox.Format.TextWrappingStyle = TextWrappingStyle.Square

# Set the position of the textbox
textBox.Format.HorizontalOrigin = HorizontalOrigin.RightMarginArea
textBox.Format.HorizontalPosition = -145.0
textBox.Format.VerticalOrigin = VerticalOrigin.Page
textBox.Format.VerticalPosition = 120.0

# Set the border style and fill color of the textbox
textBox.Format.LineColor = Color.get_DarkBlue()
textBox.Format.FillColor = Color.get_LightGray()

# Insert an image to textbox as a paragraph
para = textBox.Body.AddParagraph();
picture = para.AppendPicture("C:/Users/Administrator/Desktop/Wikipedia_Logo.png")

# Set alignment for the paragraph
para.Format.HorizontalAlignment = HorizontalAlignment.Center

# Set the size of the inserted image
picture.Height = 90.0
picture.Width = 90.0

# Insert text to textbox as the second paragraph
textRange = para.AppendText("Wikipedia is a free encyclopedia, written collaboratively by the people who use it. "
    + "Since 2001, it has grown rapidly to become the world's largest reference website,  "
    + "with 6.7 million articles in English attracting billions of views every month.")

# Set alignment for the paragraph
para.Format.HorizontalAlignment = HorizontalAlignment.Center

# Set the font of the text
textRange.CharacterFormat.FontName = "Times New Roman"
textRange.CharacterFormat.FontSize = 12.0
textRange.CharacterFormat.Italic = True

# Save the result file
document.SaveToFile("output/AddTextBox.docx", FileFormat.Docx)

Python: Add or Remove Textboxes in a Word Document

Remove a Textbox from a Word Document in Python

Spire.Doc for Python provides the Document.TextBoxes.RemoveAt(int index) method to delete a specified textbox. To delete all textboxes from a Word document, you can use the Document.TextBoxes.Clear() method. The following example shows how to remove the first textbox from a Word document.

  • Create a Document object.
  • Load a Word document using Document.LoadFromFile() method.
  • Remove the first text box using Document.TextBoxes.RemoveAt(int index) method.
  • Save the document to another file using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a Word document 
document .LoadFromFile("C:/Users/Administrator/Desktop/TextBox.docx")

# Remove the first textbox
document .TextBoxes.RemoveAt(0)

# Remove all textboxes
# document.TextBoxes.Clear()

# Save the result document
document.SaveToFile("output/RemoveTextbox.docx", FileFormat.Docx)

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: Add or Delete Pages in PDF

2023-10-30 00:55:37 Written by Koohji

Pages are the most fundamental components of a PDF document. If you want to add new information or supplemental material to an existing PDF, it is necessary to add new pages. Conversely, if there are some pages that contain incorrect or irrelevant content, you can remove them to create a more professional document. In this article, you will learn how to programmatically add or delete pages in PDF 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

Add Empty Pages to a PDF Document in Python

With Spire.PDF for Python, you can easily add a blank page to a specific position or to the end of the document using PdfDocument.Pages.Insert() or PdfDocument.Pages.Add(SizeF, PdfMargins) methods. The following are the detailed steps.

  • Create a PdfDocument object.
  • Load a sample PDF document using PdfDocument.LoadFromFile() method.
  • Create a new blank page and insert it into a specific position of the document using PdfDocument.Pages.Insert() method.
  • Create another new blank page with the specified size and margins, and then append it to the end of the document using PdfDocument.Pages.Add(SizeF, PdfMargins) method.
  • Save the result document using PdfDocument.SaveToFile() method.
  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a PdfDocument object
pdf = PdfDocument()

# Load a PDF document
pdf.LoadFromFile("Test.pdf")

# Insert a blank page to the document as the second page
pdf.Pages.Insert(1)

# Add an empty page to the end of the document
pdf.Pages.Add(PdfPageSize.A4(), PdfMargins(0.0, 0.0))

# Save the result document
pdf.SaveToFile("AddPage.pdf")
pdf.Close()

Python: Add or Delete Pages in PDF

Delete an Existing Page in a PDF Document in Python

To remove a specified page from a PDF, you can use the PdfDocument.Pages.RemoveAt() method. The following are the detailed steps.

  • Create a PdfDocument object.
  • Load a sample PDF document using PdfDocument.LoadFromFile() method.
  • Remove a specified page from the document using PdfDocument.Pages.RemoveAt() method.
  • Save the result document using PdfDocument.SaveToFile() method.
  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a PdfDocument object
pdf = PdfDocument()

# Load a PDF document
pdf.LoadFromFile("Test.pdf")

# Delete the second page of the document
pdf.Pages.RemoveAt(1)

# Save the result document
pdf.SaveToFile("DeletePage.pdf")
pdf.Close()

Python: Add or Delete Pages in 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.

Stamps are a powerful tool in PDF documents that allow users to mark and annotate specific areas or sections of a PDF file. Often used for approval, review, or to indicate a specific status, stamps can greatly enhance collaboration and document management. In PDF, stamps can take various forms, such as a simple checkmark, a customized graphic, a date and time stamp, or even a signature. In this article, you will learn how to add image stamps and dynamic stamps to a PDF document 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

Add an Image Stamp to PDF Documents in Python

Spire.PDF for Python offers the PdfRubberStampAnnotation class to represent a rubber stamp in a PDF document. In order to create the appearance of a rubber stamp, the PdfTemplate class is used. The PdfTemplate is a piece of canvas on which you can draw whatever information you want, such as text, images, date, and time.

Image stamps can include logos, signatures, watermarks, or any other custom graphics that you want to overlay onto your PDFs. The main steps to add an image stamp to PDF using Spire.PDF for Python are as follows.

  • Create a PdfDocument object.
  • Load a PDF file using PdfDocument.LoadFromFile() method.
  • Load an image that you want to stamp on PDF using PdfImage.FromFile() method.
  • Create a PdfTemplate object with the dimensions of the image.
  • Draw the image on the template using PdfTemplate.Graphics.DrawImage() method.
  • Create a PdfRubberStampAnnotation object, and set the template as its appearance.
  • Add the stamp to a specific PDF page using PdfPageBase.AnnotationsWidget.Add() method.
  • Save the document to a different file using PdfDocument.SaveToFile() method.
  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a PdfDocument object
doc = PdfDocument()

# Load a PDF document
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.pdf")

# Get a specific page
page = doc.Pages.get_Item(2)

# Load an image file
image = PdfImage.FromFile("C:\\Users\\Administrator\\Desktop\\secret.png")

# Get the width and height of the image
width = (float)(image.Width)
height = (float)(image.Height)

# Create a PdfTemplate object based on the size of the image
template = PdfTemplate(width, height, True)

# Draw image on the template
template.Graphics.DrawImage(image, 0.0, 0.0, width, height)

# Create a rubber stamp annotation, specifying its location and position
rect = RectangleF((float) (page.ActualSize.Width - width - 50), (float) (page.ActualSize.Height - height - 40), width, height)
stamp = PdfRubberStampAnnotation(rect)

# Create a PdfAppearance object
pdfAppearance = PdfAppearance(stamp)

# Set the template as the normal state of the appearance
pdfAppearance.Normal = template

# Apply the appearance to the stamp
stamp.Appearance = pdfAppearance

# Add the stamp annotation to PDF
page.AnnotationsWidget.Add(stamp)

# Save the file
doc.SaveToFile("output/ImageStamp.pdf")
doc.Close()

Python: Add Stamps to a PDF Document

Add a Dynamic Stamp to PDF in Python

Unlike static stamps, dynamic stamps can contain variable information such as the date, time, or user input. The following are the steps to create a dynamic stamp in PDF using Spire.PDF for Python.

  • Create a PdfDocument object.
  • Load a PDF file using PdfDocument.LoadFromFile() method.
  • Create a PdfTemplate object with desired size.
  • Draw strings on the template using PdfTemplate.Graphics.DrawString() method.
  • Create a PdfRubberStampAnnotation object, and set the template as its appearance.
  • Add the stamp to a specific PDF page using PdfPageBase.AnnotationsWidget.Add() method.
  • Save the document to a different file using PdfDocument.SaveToFile() method.
  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a PdfDocument object
doc = PdfDocument()

# Load a PDF document
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.pdf")

# Get a specific page
page = doc.Pages.get_Item(2)

# Create a PdfTemplate object
template = PdfTemplate(220.0, 50.0, True)

# Create two fonts
font1 = PdfTrueTypeFont("Elephant", 16.0, 0, True)
font2 = PdfTrueTypeFont("Times New Roman", 10.0, 0, True)

# Create a solid brush and a gradient brush
solidBrush = PdfSolidBrush(PdfRGBColor(Color.get_Blue()))
rectangle1 = RectangleF(PointF(0.0, 0.0), template.Size)
linearGradientBrush = PdfLinearGradientBrush(rectangle1, PdfRGBColor(Color.get_White()), PdfRGBColor(Color.get_LightBlue()), PdfLinearGradientMode.Horizontal)

# Create a pen
pen = PdfPen(solidBrush)

# Create a rounded rectangle path
CornerRadius = 10.0
path = PdfPath()
path.AddArc(template.GetBounds().X, template.GetBounds().Y, CornerRadius, CornerRadius, 180.0, 90.0)
path.AddArc(template.GetBounds().X + template.Width - CornerRadius, template.GetBounds().Y, CornerRadius, CornerRadius, 270.0, 90.0)
path.AddArc(template.GetBounds().X + template.Width - CornerRadius, template.GetBounds().Y + template.Height - CornerRadius, CornerRadius, CornerRadius, 0.0, 90.0)
path.AddArc(template.GetBounds().X, template.GetBounds().Y + template.Height - CornerRadius, CornerRadius, CornerRadius, 90.0, 90.0)
path.AddLine(template.GetBounds().X, template.GetBounds().Y + template.Height - CornerRadius, template.GetBounds().X, template.GetBounds().Y + CornerRadius / 2)

# Draw path on the template
template.Graphics.DrawPath(pen, path)
template.Graphics.DrawPath(linearGradientBrush, path)

# Draw text on the template
string1 = "APPROVED\n"
string2 = "By Marketing Manager at " + DateTime.get_Now().ToString("HH:mm, MMM dd, yyyy")
template.Graphics.DrawString(string1, font1, solidBrush, PointF(5.0, 5.0))
template.Graphics.DrawString(string2, font2, solidBrush, PointF(2.0, 28.0))

# Create a rubber stamp, specifying its size and location
rectangle2 = RectangleF((float) (page.ActualSize.Width - 220.0 - 50.0), (float) (page.ActualSize.Height - 50.0 - 100.0), 220.0, 50.0)
stamp = PdfRubberStampAnnotation(rectangle2)

# Create a PdfAppearance object and apply the template as its normal state
apprearance = PdfAppearance(stamp)
apprearance.Normal = template

# Apply the appearance to stamp
stamp.Appearance = apprearance

# Add the stamp annotation to annotation collection
page.AnnotationsWidget.Add(stamp)

# Save the file
doc.SaveToFile("output/DynamicStamp.pdf", FileFormat.PDF)
doc.Dispose()

Python: Add Stamps to 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.

Page 21 of 26
page 21