Adding and deleting slides in PowerPoint are essential actions that allow presenters to control the structure and content of their presentations. Adding slides provides the opportunity to expand and enhance the presentation by introducing new topics or providing supporting information. On the other hand, deleting slides helps streamline the presentation by removing redundant, repetitive, or irrelevant content. In this article, we will demonstrate how to add or delete slides 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 a New Slide at the End of the PowerPoint Document in Python

Spire.Presentation for Python provides the Presentation.Slides.Append() method to add a new slide after the last 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.
  • Add a new blank slide at the end of the presentation using Presentation.Slides.Append() 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()

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

# Add a new slide at the end of the presentation
presentation.Slides.Append()

# Save the result presentation to a .pptx file
presentation.SaveToFile("AddSlide.pptx", FileFormat.Pptx2013)
presentation.Dispose()

Python: Add or Delete Slides in PowerPoint Presentations

Insert a New Slide Before a Specific Slide in PowerPoint in Python

You can use the Presentation.Slides.Insert() method to insert a new slide before 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.
  • Insert a blank slide before a specific slide using Presentation.Slides.Insert() 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()

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

# Insert a blank slide before the second slide
presentation.Slides.Insert(1)

# Save the result presentation to a .pptx file
presentation.SaveToFile("InsertSlide.pptx", FileFormat.Pptx2013)
presentation.Dispose()

Python: Add or Delete Slides in PowerPoint Presentations

Delete a Specific Slide from a PowerPoint Document in Python

To delete a specific slide from a PowerPoint presentation, you can use the Presentation.Slides.RemoveAt() method. The detailed steps are as follows.

  • Create an object of the Presentation class.
  • Load a PowerPoint presentation using Presentation.LoadFromFile() method.
  • Remove a specific slide from the presentation using Presentation.Slides.RemoveAt() 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()

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

# Remove the first slide
presentation.Slides.RemoveAt(0)

# Save the result presentation to a .pptx file
presentation.SaveToFile("RemoveSlide.pptx", FileFormat.Pptx2013)
presentation.Dispose()

Python: Add or Delete Slides in PowerPoint Presentations

Apply for a Temporary License

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

Setting proper margins is an essential step in creating professional Word documents. Margins may seem like a small detail, but they play a vital role in improving the readability and visual appeal of a document. By defining the space around content, margins help maintain a consistent and balanced layout, prevent text from being truncated, and make documents look more organized and aesthetically pleasing. This article will show how to use Spire.Doc for Python to set page margins for 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

Set the Page Margins of a Word Document

Spire.Doc for Python provides properties under the Margins class that can be used to set margins for each side of a document separately or to set the same margins for all sides. One important thing to note is that the margins are set based on sections. For consistent margins throughout the document, it is necessary to iterate through each section of the document to set the margins. Below are the detailed steps for setting page margins:

  • Create an object of Document class.
  • Load a Word document using Document.LoadFromFile() method.
  • Loop through the sections of the document.
  • Get a section using Document.Sections.get_Item() method.
  • Get the margins of the section using Section.PageSetup.Margins property.
  • Set the top, bottom, left, and right margin using property under Margins class.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create an object of Document class
doc = Document()

# Load a Word document
doc.LoadFromFile("Sample.docx")

# Loop thorugh the sections of document
for i in range(doc.Sections.Count):
    # Get a section
    section = doc.Sections.get_Item(i)
    # Get the margins of the section
    margins = section.PageSetup.Margins
    # Set the top, bottom, left, and right margins
    margins.Top = 17.9
    margins.Bottom = 17.9
    margins.Left = 20.9
    margins.Right = 20.9
    # margins.All = 17.9

# Save the document
doc.SaveToFile("output/SetPageMargins.docx", FileFormat.Auto)

Python: Set Page Margins for 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.

Precisely Extract Text from PDF using Python

PDF files are everywhere—from contracts and research papers to eBooks and invoices. While they preserve formatting perfectly, extracting text from PDFs can be challenging, especially with large or complex documents. Manual copying is not only slow but often inaccurate.

Whether you’re a developer automating workflows, a data analyst processing content, or simply someone needing quick text extraction, programmatic methods can save you valuable time and effort.

In this comprehensive guide, you’ll learn how to extract text from PDF files in Python using Spire.PDF for Python — a powerful and easy-to-use PDF processing library. We’ll cover extracting all text, targeting specific pages or areas, ignoring hidden text, and capturing layout details such as text position and size.

Table of Contents

Why Extract Text from PDF Files

Text extraction from PDFs is essential for many use cases, including:

  • Automating data entry and document processing
  • Enabling full-text search and indexing
  • Performing data analysis on reports and surveys
  • Extracting content for machine learning and NLP
  • Converting PDFs to other editable formats

Install Spire.PDF for Python: Powerful PDF Parser Library

Spire.PDF for Python is a comprehensive and easy-to-use PDF processing library that simplifies all your PDF manipulation needs. It offers advanced text extraction capabilities that work seamlessly with both simple and complex PDF documents.

Installation

The library can be installed easily via pip. Open your terminal and run the following command:

pip install spire.pdf

Need help with the installation? Follow this step-by-step guide: How to Install Spire.PDF for Python on Windows

Extract Text from PDF (Basic Example)

If you just want to quickly read all the text from a PDF, this simple example shows how to do it. It iterates over each page, extracts the full text using PdfTextExtractor, and saves it to a text file with spacing and line breaks preserved.

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/Terms of service.pdf')

# Prepare a variable to hold the extracted text
all_text = ""

# Create a PdfTextExtractOptions object
extractOptions = PdfTextExtractOptions()
# Extract all text including whitespaces
extractOptions.IsExtractAllText = True

# Loop through all pages and extract text
for i in range(doc.Pages.Count):
    page = doc.Pages.get_Item(i)
    textExtractor = PdfTextExtractor(page)
    text = textExtractor.ExtractText(extractOptions)
    # Append text from each page
    all_text += text + "\n"

# Write all extracted text to a file
with open('output/TextOfAllPages.txt', 'w', encoding='utf-8') as file:
    file.write(all_text)

Advanced Text Extraction Features

For greater control over what and how text is extracted, Spire.PDF for Python offers advanced options. You can selectively extract content from specific pages or regions, or even with layout details, such as text position and size, to better suit your specific data processing needs.

Retrieve Text from Selected Pages

Instead of processing an entire PDF, you can target specific pages for text extraction. This is especially useful for large documents where only certain sections are relevant for your task.

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/Terms of service.pdf')

# Create a PdfTextExtractOptions object and enable full text extraction
extractOptions = PdfTextExtractOptions()
# Extract all text including whitespaces
extractOptions.IsExtractAllText = True

# Get a specific page (e.g., page 2)
page = doc.Pages.get_Item(1)

# Create a PdfTextExtractor object
textExtractor = PdfTextExtractor(page)

# Extract text from the page
text = textExtractor.ExtractText(extractOptions)

# Write the extracted text to a file using UTF-8 encoding
with open('output/TextOfPage.txt', 'w', encoding='utf-8') as file:
    file.write(text)

Retrieve Text from Selected Pages Output

Get Text from Defined Area

When dealing with structured documents like forms or invoices, extracting text from a specific region can be more efficient. You can define a rectangular area and extract only the text within that boundary on the page.

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/Terms of service.pdf')

# Get a specific page (e.g., page 2)
page = doc.Pages.get_Item(1)

# Create a PdfTextExtractor object
textExtractor = PdfTextExtractor(page)

# Create a PdfTextExtractOptions object
extractOptions = PdfTextExtractOptions()

# Define the rectangular area to extract text from
# RectangleF(left, top, width, height)
extractOptions.ExtractArea = RectangleF(0.0, 100.0, 890.0, 80.0)

# Extract text from the specified area, keeping white spaces
text = textExtractor.ExtractText(extractOptions)

# Write the extracted text to a file using UTF-8 encoding
with open('output/TextOfRectangle.txt', 'w', encoding='utf-8') as file:
    file.write(text)

Retrieve Text from Defined Area Output

Ignore Hidden Text During Extraction

Some PDFs contain hidden or invisible text, often used for accessibility or OCR layers. You can choose to ignore such content during extraction to focus only on what is actually visible to users.

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/Terms of service.pdf')

# Create a PdfTextExtractOptions object
extractOptions = PdfTextExtractOptions()
# Ignore hidden text during extraction
extractOptions.IsShowHiddenText = False

# Get a specific page (e.g., page 2)
page = doc.Pages.get_Item(1)

# Create a PdfTextExtractor object
textExtractor = PdfTextExtractor(page)

# Extract text from the page
text = textExtractor.ExtractText(extractOptions)

# Write the extracted text to a file using UTF-8 encoding
with open('output/ExcludeHiddenText.txt', 'w', encoding='utf-8') as file:
    file.write(text)

Retrieve Text with Position (Coordinates) and Size Information

For layout-sensitive applications—such as converting PDF content into editable formats or reconstructing page structure—you can extract text along with its position and size. This provides precise control over how content is interpreted and used.

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/Terms of service.pdf')

# Loop through all pages of the document
for i in range(doc.Pages.Count):
    page = doc.Pages.get_Item(i)

    # Create a PdfTextFinder object for the current page
    finder = PdfTextFinder(page)

    # Find all text fragments on the page
    fragments = finder.FindAllText()

    print(f"Page {i + 1}:")

    # Loop through all text fragments
    for fragment in fragments:
        # Extract text content from the current text fragment
        text = fragment.Text

        # Get bounding rectangles with position and size
        rects = fragment.Bounds

        print(f'Text: "{text}"')

        # Iterate through all rectangles
        for rect in rects:
            # Print the position and size information of the current rectangle
            print(f"Position: ({rect.X}, {rect.Y}), Size: ({rect.Width} x {rect.Height})")

        print()

Conclusion

Extracting text from PDF files in Python becomes efficient and flexible with Spire.PDF for Python. Whether you need to process entire documents or extract text from specific pages or regions, Spire.PDF provides a robust set of tools to meet your needs. By automating text extraction, you can streamline workflows, power intelligent search systems, or prepare data for analysis and machine learning.

FAQs

Q1: Can text be extracted from password-protected PDFs?

A1: Yes, Spire.PDF for Python can open and extract text from secured files by providing the correct password when loading the PDF document.

Q2: Is batch text extraction from multiple PDFs supported?

A2: Yes, you can programmatically iterate through a directory of PDF files and apply text extraction to each file efficiently using Spire.PDF for Python.

Q3: Is it possible to extract images or tables from PDFs?

A3: While this guide focuses on text extraction, Spire.PDF for Python also supports image extraction and table extraction.

Q4: Can text be extracted from scanned (image-based) PDFs?

A4: Extracting text from scanned PDFs requires OCR (Optical Character Recognition). Spire.PDF for Python does not include built-in OCR, but you can combine it with an OCR library like Spire.OCR for image-to-text conversion.

Get a Free License

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

PDF files often contain critical embedded images (e.g., charts, diagrams, scanned documents). For developers, knowing how to extract images from PDF in Python allows them to repurpose graphical content for automated report generation or feed these visuals into machine learning models for analysis and OCR tasks.

Visual guide for Extract Images from PDF Python

This article explores how to leverage the Spire.PDF for Python library to extract images from PDF files via Python, covering the following aspects:

Installation & Environment Setup

Before you start using Spire.PDF for Python to extract images from PDF, make sure you have the following in place:

  • Python Environment: Ensure that you have Python installed on your system. It is recommended to use the latest stable version for the best compatibility and performance.

  • Spire.PDF for Python Library: You need to install the Python PDF SDK, and the easiest way is using pip, the Python package installer.

    Open your command prompt or terminal and run the following command:

pip install Spire.PDF

How to Extract Images from PDFs using Python

Example 1: Extract Images from a PDF Page

Here’s a complete Python script to extract and save images from a specified page in PDF:

from spire.pdf.common import *
from spire.pdf import *

# Create a PdfDocument instance
pdf = PdfDocument()

# Load a PDF file
pdf.LoadFromFile("template1.pdf")

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

# Create a PdfImageHelper instance
imageHelper = PdfImageHelper()

# Get the image information on the page
imageInfo = imageHelper.GetImagesInfo(page)

# Iterate through the image information
for i in range(0, len(imageInfo)):
    # Save images to file
    imageInfo[i].Image.Save("PageImage\\Image" + str(i) + ".png")

# Release resources
pdf.Dispose()

Key Steps Explained:

  • Load the PDF: Use the LoadFromFile() method to load a PDF file.
  • Access a Page: Access a specified PDF page by index.
  • Extract Image information:
    • Create a PdfImageHelper instance to facilitate image extraction.
    • Use the GetImagesInfo() method to retrieve image information from the specified page, and return a list of PdfImageInfo objects.
  • Save Images to Files:
    • Loops through all detected images on the page
    • Use the PdfImageInfo[].Image.Save() method to save the image to disk.

Output:

Extract all images from the first page in a PDF

Example 2: Extract All Images from a PDF File

Building on the single-page extraction method, you can iterate through all pages of the PDF document to extract every embedded image.

Python code example:

from spire.pdf.common import *
from spire.pdf import *

# Create a PdfDocument instance
pdf = PdfDocument()

# Load a PDF file
pdf.LoadFromFile("template1.pdf")

# Create a PdfImageHelper instance
imageHelper = PdfImageHelper()

# Iterate through the pages in the document
for i in range(0, pdf.Pages.Count):
    # Get the current page
    page = pdf.Pages.get_Item(i)
    # Get the image information on the page
    imageInfo = imageHelper.GetImagesInfo(page)
    # Iterate through the image information items
    for j in range(0, len(imageInfo)):
        # Save the current image to file
        imageInfo[j].Image.Save(f"Images\\Image{i}_{j}.png")

# Release resources
pdf.Close()

Output:

Extract all images from an entire PDF file.

Handle Different Image Formats While Extraction

Spire.PDF for Python supports extracting images in various formats such as PNG, JPG/JPEG, BMP, etc. When saving the extracted images, you can choose the appropriate format based on your needs.

Common Image Formats:

Format Best Use Cases PDF Extraction Notes
JPG/JPEG Photos, scanned documents Common in PDFs; quality loss on re-compress
PNG Web graphics, diagrams, screenshots Preserves transparency; larger file sizes
BMP Windows applications, temp storage Rare in modern PDFs; avoid for web use
TIFF Archiving, print, OCR input Ideal for document preservation; multi-page
EMF Windows vector editing Editable in Illustrator/Inkscape

Frequently Asked Questions

Q1: Is Spire.PDF for Python a free library?

Spire.PDF for Python offers both free and commercial versions. The free version has limitations, such as a maximum of 10 pages per PDF. For commercial use or to remove these restrictions, you can request a trial license here.

Q2: Can I extract images from a specified page range only?

Yes. Instead of iterating through all pages, specify the page indices you want. For example, to extract images from the pages 2 to 5:

# Extract images from pages 2 to 5
for i in range(1, 4): # Pages are zero-indexed
    page = pdf.Pages.get_Item(i)
    # Process images as before

Q3: Is it possible to extract text from images?

Yes. For scanned PDF files, after extracting the images, you can extract the text in the images in conjunction with the Spire.OCR for Python library.

A step-by-step guide: How to Extract Text from Image Using Python (OCR Code Examples)


Conclusion (Extract Text and More)

Spire.PDF simplifies image extraction from PDF in Python with minimal code. By following this guide, you can:

  • Extract images from single pages or entire PDF documents.
  • Save images from PDF in various formats (PNG, JPG, BMP or TIFF).

As a PDF document can contain different elements, the Python PDF library is also capable of:

Python: Add Bookmarks to a Word Document

2023-10-07 01:13:31 Written by Koohji

Adding bookmarks to Word documents is a useful feature that allows users to mark specific locations within their documents for quick reference or navigation. Bookmarks serve as virtual placeholders, making it easier to find and revisit important sections of a document without scrolling through lengthy pages. In this article, you will learn how to add bookmarks to 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 Bookmarks to a Paragraph in Python

Spire.Doc for Python offers the BookmarkStart to represent the start of a bookmark and the BookmarkEnd to represent the end of a bookmark. To bookmark a paragraph, a BookmarkStart object is placed at the beginning of the paragraph and a BookmarkEnd object is appended at the end of the paragraph. The following are the detailed steps.

  • Create a Document object.
  • Load a Word file using Document.LoadFromFile() method.
  • Get a specific paragraph through Document.Sections[index].Paragraphs[index] property.
  • Create a BookmarkStart using Paragraph.AppendBookmarkStart() method and insert it at the beginning of the paragraph using Paragraph.Items.Insert() method.
  • Append a BookmarkEnd at the end of the paragraph using Paragraph.AppendBookmarkEnd() method.
  • Save the document to a different Word file using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
doc = Document()

# Load a sample Word file
doc.LoadFromFile('C:/Users/Administrator/Desktop/input.docx')

# Get the second paragraph
paragraph = doc.Sections[0].Paragraphs[2]

# Create a bookmark start
start = paragraph.AppendBookmarkStart('myBookmark')

# Insert it at the beginning of the paragraph
paragraph.Items.Insert(0, start)

# Append a bookmark end at the end of the paragraph
paragraph.AppendBookmarkEnd('myBookmark')

# Save the file
doc.SaveToFile('output/AddBookmarkToParagraph.docx', FileFormat.Docx2019)

Python: Add Bookmarks to a Word Document

Add Bookmarks to Selected Text in Python

To bookmark a piece of text, you need first to get the text from the document and get its position inside its owner paragraph. And then place a BookmarkStart before it and a BookmarEnd after it. The detailed steps are as follows.

  • Create a Document object.
  • Load a Word file using Document.LoadFromFile() method.
  • Find the string to be marked from the document.
  • Get its owner paragraph and its position inside the paragraph.
  • Insert a BookmarkStart before the text and a BookmarkEnd after the text.
  • Save the document to a different Word file using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
doc = Document()

# Load a sample Word file
doc.LoadFromFile('C:/Users/Administrator/Desktop/input.docx')

# Specify the string to find
stringToFind = 'programming paradigms'

# Find the selected text from the document
finds = doc.FindAllString(stringToFind, False, True)
specificText = finds[0]

# Find the paragraph where the text is located
paragraph = specificText.GetAsOneRange().OwnerParagraph

# Get the index of the text in the paragraph
index = paragraph.ChildObjects.IndexOf(specificText.GetAsOneRange())

# Create a bookmark start
start = paragraph.AppendBookmarkStart("myBookmark")

# Insert the bookmark start at the index position
paragraph.ChildObjects.Insert(index, start)

# Create a bookmark end
end = paragraph.AppendBookmarkEnd("myBookmark")

# Insert the bookmark end at the end of the selected text
paragraph.ChildObjects.Insert(index + 2, end)

# Save the document to a different file
doc.SaveToFile("output/AddBookmarkToSelectedText.docx", FileFormat.Docx2019)

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

Large PDF files can sometimes be cumbersome to handle, especially when sharing or uploading them. Splitting a large PDF file into multiple smaller PDFs reduces the file size, making it more manageable and quicker to open and process. In this article, we will demonstrate how to split PDF documents 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

Split a PDF File into Multiple Single-Page PDFs in Python

Spire.PDF for Python offers the PdfDocument.Split() method to divide a multi-page PDF document into multiple single-page PDF files. The following are the detailed steps.

  • Create a PdfDocument object.
  • Load a PDF document using PdfDocument.LoadFromFile() method.
  • Split the document into multiple single-page PDFs using PdfDocument.Split() method.
  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a PdfDocument object
doc = PdfDocument()
# Load a PDF file
doc.LoadFromFile("Sample.pdf")

# Split the PDF file into multiple single-page PDFs
doc.Split("Output/SplitDocument-{0}.pdf", 1)

# Close the PdfDocument object
doc.Close()

Python: Split a PDF File into Multiple PDFs

Split a PDF File by Page Ranges in Python

To split a PDF file into two or more PDF files by page ranges, you need to create two or more new PDF files, and then import the specific page or range of pages from the source PDF into the newly created PDF files. The following are the detailed steps.

  • Create a PdfDocument object.
  • Load a PDF document using PdfDocument.LoadFromFile() method.
  • Create three PdfDocument objects.
  • Import the first page from the source file into the first document using PdfDocument.InsertPage() method.
  • Import pages 2-4 from the source file into the second document using PdfDocument.InsertPageRange() method.
  • Import the remaining pages from the source file into the third document using PdfDocument.InsertPageRange() method.
  • Save the three documents using PdfDocument.SaveToFile() method.
  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a PdfDocument object
doc = PdfDocument()
# Load a PDF file
doc.LoadFromFile("Sample.pdf")

# Create three PdfDocument objects
newDoc_1 = PdfDocument()
newDoc_2 = PdfDocument()
newDoc_3 = PdfDocument()

# Insert the first page of the source file into the first document
newDoc_1.InsertPage(doc, 0)

# Insert pages 2-4 of the source file into the second document
newDoc_2.InsertPageRange(doc, 1, 3)

# Insert the rest pages of the source file into the third document
newDoc_3.InsertPageRange(doc, 4, doc.Pages.Count - 1)

# Save the three documents
newDoc_1.SaveToFile("Output1/Split-1.pdf")
newDoc_2.SaveToFile("Output1/Split-2.pdf")
newDoc_3.SaveToFile("Output1/Split-3.pdf")

# Close the PdfDocument objects
doc.Close()
newDoc_1.Close()
newDoc_2.Close()
newDoc_3.Close()

Python: Split a PDF File into Multiple PDFs

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 editing restriction function is a feature in Word documents that allows users to control and limit the editing capabilities and editable areas. It is commonly used to protect sensitive or important document from unauthorized or substandard modifications. By applying editing restrictions, the document owner can specify what types of changes can be made and which part of the document can be edited to protect the document and facilitate collaborating, information gathering, etc. This article is going to show how to restrict Word document editing and remove document editing restrictions 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

Restrict Editing of Entire Word Documents with Passwords

There are four types or editing restrictions in Word documents: No changes (Read only), Tracked changes, Comments, and Filling in forms. Spire.Doc for Python provides the Document.Protect() method set editing restrictions and ProtectionType Enum to represent the restriction types.

Here is a list of the ProtectionType Enum and the corresponding editing restrictions:

Enum Editing Restriction Description
ProtectionType.AllowOnlyReading No changes (Read only) Allow reading only.
ProtectionType.AllowOnlyRevisions Tracked changes Allow tracked changes only.
ProtectionType.AllowOnlyComments Comments Allow comments only.
ProtectionType.AllowOnlyFormFields Filling in forms Allow filling out forms only.
ProtectionType.NoProtection None No restrictions.

The steps for setting editing restrictions with a password on Word documents are as follows:

  • Create an object of Document class.
  • Load a Word document using Document.LoadFromFile() method.
  • Set specified editing restrictions on the document using Document.Protect(type:ProtectionType, password:str) method.
  • Save the document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create an object of Document class
doc = Document()

# Load a Word document
doc.LoadFromFile("Sample.docx")

# Set the editing restriction type to No changes (Read only)
doc.Protect(ProtectionType.AllowOnlyReading, "password")

# Set the editing restriction type to Tracked changes
# doc.Protect(ProtectionType.AllowOnlyRevisions, "password")

# Set the editing restriction type to Comments
# doc.Protect(ProtectionType.AllowOnlyComments, "password")

# Set the editing restriction type to Filling in forms
# doc.Protect(ProtectionType.AllowOnlyFormFields, "password")

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

Python: Set or Remove Word Document Editing Restrictions

Set Exceptions to Word Document Editing Restrictions

Users can add exceptions (unrestricted areas) when setting editing restrictions on Word documents by inserting permission starting and ending tags. The details steps are as follows:

  • Create an object of Document class.
  • Load a Word document using Document.LoadFromFile() method.
  • Get the first section using Document.Sections.get_Item() method.
  • Create an object of PermissionStart class and an object of PermissionEnd class.
  • Insert the permission start tag and the end tag to the document using Paragraph.ChildObjects.Insert() method and Paragraph.ChildObjects.Add() method.
  • Set the editing restriction using Document.Protect() method.
  • Save the document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create an object of Document class
doc = Document()

# Load a Word document
doc.LoadFromFile("Sample.docx")

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

# Create a permission start tag and an end tag
start = PermissionStart(doc, "exception1")
end = PermissionEnd(doc, "exception1")

# Insert the permission start tag and the end tag to the first section
paragraph = section.Paragraphs.get_Item(1)
paragraph.ChildObjects.Insert(0,start)
paragraph.ChildObjects.Add(end)

# Set the editing restriction
doc.Protect(ProtectionType.AllowOnlyReading, "password")

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

Python: Set or Remove Word Document Editing Restrictions

Remove Editing Restrictions from Word Documents

To remove the editing restrictions of a document, simply set the editing restriction type to no restriction using the Document.Protect() method. The detailed steps are as follows:

  • Create an object of Document class.
  • Load a Word document using Document.LoadFromFile() method.
  • Remove the restriction by setting the restriction type to None using Document.Protect() method.
  • Save the document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create an object of Document class
doc = Document()

# Load a Word document
doc.LoadFromFile("output/EditingRestrictions.docx")

# Remove the editing restriction by set the restriction type to None
doc.Protect(ProtectionType.NoProtection)

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

Python: Set or Remove Word Document Editing Restrictions

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 Examples for Converting Images to PDF

Converting images to PDF programmatically is a common task in document management, as it enhances organization, facilitates sharing, and ensures efficient archiving. By consolidating various image formats into a single PDF document, users can easily manage and distribute their visual content.

In this article, we will explore how to convert a variety of image formats —including PNG , JPEG , TIFF , and SVG —into PDF files using Spire.PDF for Python. We’ll provide detailed instructions and code examples to guide you through the conversion process, highlighting the flexibility and power of this library for handling different image types.

Table of Contents:

1. Why Convert Image to PDF?

PDFs are preferred for their portability, security, and consistent formatting across devices. Converting images to PDF offers several benefits:

  • Preservation of Quality: PDFs retain image resolution, ensuring no loss in clarity.
  • Easier Sharing: A single PDF can combine multiple images, simplifying distribution.
  • Document Standardization: Converting images to PDF ensures compatibility with most document management systems.

Whether you're archiving scanned documents or preparing a portfolio, converting images to PDF enhances usability.

2. Introducing Spire.PDF: Python Image-to-PDF Library

Spire.PDF for Python is a robust library that enables PDF creation, manipulation, and conversion. Key features include:

  • Support for multiple image formats (PNG, JPEG, BMP, SVG, and more).
  • Flexible page customization (size, margins, orientation).
  • Batch processing and multi-image merging.
  • Advanced options like watermarking and encryption (beyond basic conversion).

To install the library, use:

pip install Spire.PDF

3. Convert PNG or JPEG to PDF in Python

3.1 Generate PDF Matching Image Dimensions

To convert a PNG or JPEG image to PDF while preserving its original size, we start by creating a PdfDocument object, which serves as the container for our PDF. We set the page margins to zero, ensuring that the image will fill the entire page.

After loading the image, we obtain its dimensions to create a new page that matches these dimensions. Finally, we draw the image on the page and save the document to a PDF file. This approach guarantees pixel-perfect conversion without resizing or distortion.

The following code demonstrates how to generate a PDF that perfectly matches your image’s size:

from spire.pdf.common import *
from spire.pdf import *

# Create a PdfDocument object
document = PdfDocument()

# Set the page margins to 0
document.PageSettings.SetMargins(0.0)

# Load an image file
image = PdfImage.FromFile("C:\\Users\\Administrator\\Desktop\\robot.jpg")
    
# Get the image width and height
imageWidth = image.PhysicalDimension.Width
imageHeight = image.PhysicalDimension.Height

# Add a page that has the same size as the image
page = document.Pages.Add(SizeF(imageWidth, imageHeight))

# Draw image at (0, 0) of the page
page.Canvas.DrawImage(image, 0.0, 0.0)
      
# Save to file
document.SaveToFile("output/ImageToPdf.pdf")

# Dispose resources
document.Dispose()

Output:

Generated PDF file that has the same size as the image file.

3.2 Custom PDF Layouts and Image Position

To customize the PDF page size and margins, a few modifications to the code are needed. In this example, we set the page size to A4, adjusting the margins accordingly. The image is centered on the page by calculating its position based on the page dimensions. This method creates a more polished layout for the PDF.

The code below shows how to customize PDF settings and position images during conversion:

from spire.pdf.common import *
from spire.pdf import *

# Create a PdfDocument object
document = PdfDocument()

# Set the page margins to 5
document.PageSettings.SetMargins(5.0)

# Define page size (A4 or custom)
document.PageSettings.Size = PdfPageSize.A4()

# Add a new page to the document
page = document.Pages.Add()

# Load the image from file
image = PdfImage.FromFile("C:\\Users\\Administrator\\Desktop\\robot.jpg")

# Get the image dimensions
imageWidth = image.PhysicalDimension.Width
imageHeight = image.PhysicalDimension.Height

# Calculate centered position for the image
x = (page.GetClientSize().Width - imageWidth) / 2
y = (page.GetClientSize().Height - imageHeight) / 2 

# Draw the image at the calculated position
page.Canvas.DrawImage(image, x, y, imageWidth, imageHeight)

# Save to a PDF file
document.SaveToFile("output/ImageToPdf.pdf")

# Release resources
document.Dispose()

Output:

An image placed at the center of an A4 page in a PDF.

4. Convert Multi-Page TIFF to PDF in Python

TIFF files are widely used for high-resolution images, making them suitable for applications such as document scanning and medical imaging. However, Spire.PDF does not support TIFF images natively. To handle TIFF files, we can use the Python Imaging Library (PIL) , which can be installed with the following command:

pip install Pillow

Using PIL, we can access each frame of a TIFF file, temporarily save it as a PNG, and then draw each PNG onto a PDF. This method ensures that each frame is added as a separate page in the PDF, preserving the original quality and layout.

Here is the code snippet for converting a multi-page TIFF to PDF in Python:

from spire.pdf.common import *
from spire.pdf import *
from PIL import Image
import io

# Create a PdfDocument object
document = PdfDocument()

# Set the page margins to 0
document.PageSettings.SetMargins(0.0)

# Load a TIFF image
tiff_image = Image.open("C:\\Users\\Administrator\\Desktop\\TIFF.tiff")

# Iterate through the frames in it
for i in range(getattr(tiff_image, 'n_frames', 1)):

    # Go to the current frame
    tiff_image.seek(i)
    
    # Extract the image of the current frame
    frame_image = tiff_image.copy()

    # Save the image to a PNG file
    frame_image.save(f"temp/output_frame_{i}.png")
    
    # Load the image file to PdfImage
    image = PdfImage.FromFile(f"temp/output_frame_{i}.png")

    # Get image width and height
    imageWidth = image.PhysicalDimension.Width
    imageHeight = image.PhysicalDimension.Height

    # Add a page to the document
    page = document.Pages.Add(SizeF(imageWidth, imageHeight))

    # Draw image at (0, 0) of the page
    page.Canvas.DrawImage(image, 0.0, 0.0)

# Save the document to a PDF file
document.SaveToFile("Output/TiffToPdf.pdf",FileFormat.PDF)

# Dispose resources
document.Dispose()

Output:

Screenshot of the input TIFF file and output PDF document.

5. Convert Scalable SVG to PDF in Python

SVG files are vector graphics that provide scalability without loss of quality, making them ideal for web graphics and print media. In this example, we create a PdfDocument object and load an SVG file directly into it. Spire.PDF library efficiently handles the conversion, allowing for quick and straightforward saving of the SVG as a PDF with minimal code.

Below is the code snippet for converting an SVG file to a PDF:

from spire.pdf.common import *
from spire.pdf import *

# Create a PdfDocument object
document = PdfDocument()

# Load an SVG file
document.LoadFromSvg("C:\\Users\\Administrator\\Desktop\\SVG.svg")

# Save the SVG file to PDF
document.SaveToFile("output/SvgToPdf.pdf", FileFormat.PDF)

# Dispose resources
document.Dispose()

Tip : To combine multiple SVG files into a single PDF, convert them separately and then merge the resulting PDFs. For guidance, check out this article: How to Merge PDF Documents in Python.

Output:

Screenshot of the input SVG file and output PDF document.

6. Merge Multiple Images into One PDF

This process involves iterating through images in a specified directory, loading each one, and creating corresponding pages in the PDF document. Each page is formatted to match the image dimensions, preventing any loss or distortion. Finally, each image is drawn onto its respective page.

Code example for combining a folder of images into a single PDF:

from spire.pdf.common import *
from spire.pdf import *
import os

# Create a PdfDocument object
doc = PdfDocument()

# Set the page margins to 0
doc.PageSettings.SetMargins(0.0)

# Get the folder where the images are stored
path = "C:\\Users\\Administrator\\Desktop\\Images\\"
files = os.listdir(path)

# Iterate through the files in the folder
for root, dirs, files in os.walk(path):
    for file in files:

        # Load a particular image 
        image = PdfImage.FromFile(os.path.join(root, file))
    
        # Get the image width and height
        width = image.PhysicalDimension.Width
        height = image.PhysicalDimension.Height

        # Add a page that has the same size as the image
        page = doc.Pages.Add(SizeF(width, height))

        # Draw image at (0, 0) of the page
        page.Canvas.DrawImage(image, 0.0, 0.0, width, height)
      
# Save to file
doc.SaveToFile("output/CombineImages.pdf")
doc.Dispose()

Output:

Screenshot of the input image files in a folder and the output PDF document.

7. Conclusion

Converting images to PDF in Python using the Spire.PDF library is a straightforward task that can be accomplished through various methods for different image formats. Whether you need to convert single images, customize layouts, or merge multiple images, Spire.PDF provides the necessary tools to achieve your goals efficiently. With just a few lines of code, you can create high-quality PDFs from images, enhancing your document management capabilities.

8. FAQs

Q1: Can I convert images in bulk using Spire.PDF?

Yes, Spire.PDF allows you to iterate through directories and convert multiple images to a single PDF or individual PDFs, making bulk conversions easy.

Q2: What image formats does Spire.PDF support?

Spire.PDF supports various image formats, including PNG, JPEG, BMP, and SVG, providing versatility for different use cases.

Q3: Can I customize the PDF layout?

Absolutely. You can set margins, page sizes, and positions of images within the PDF for a tailored layout that meets your requirements.

Q4: Does converting an image to PDF reduce its quality?

No - when using Spire.PDF with default settings, the original image data is embedded without compression.

Get a Free License

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

Images are universally compatible and can be easily shared across various platforms, devices, and applications. By converting PowerPoint slides to images, you can distribute your content effortlessly via email, messaging apps, websites, or social media platforms. This makes your presentation accessible to a wider audience and ensures that it can be viewed by anyone, regardless of the software or device they are using. In this article, we will explain how to convert PowerPoint to images 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

Convert PowerPoint Presentation to JPG, PNG or BMP Images in Python

Spire.Presentation for Python offers the ISlide.SaveAsImage() method which enables you to convert the slides in a PowerPoint presentation to image files in formats like PNG, JPG or BMP with ease. The detailed steps are as follows:

  • Create a Presentation object.
  • Load a PowerPoint presentation using Presentation.LoadFromFile() method.
  • Loop through the slides in the presentation.
  • Save each slide to an image stream using ISlide.SaveAsImage() method.
  • Save the image stream to a JPG, PNG or BMP file using Stream.Save() 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")

# Loop through the slides in the presentation
for i, slide in enumerate(presentation.Slides):
    # Specify the output file name
    fileName ="Output/ToImage_" + str(i) + ".png"
    # Save each slide as a PNG image
    image = slide.SaveAsImage()
    image.Save(fileName)
    image.Dispose()

presentation.Dispose()

Python: Convert PowerPoint to Images (PNG, JPG, BMP, SVG)

Convert PowerPoint Presentation to JPG, PNG or BMP Images with a Specific Size in Python

You can convert the slides in a PowerPoint presentation to images with a specific size using ISlide.SaveAsImageByWH() method. The detailed steps are as follows:

  • Create a Presentation object.
  • Load a PowerPoint presentation using Presentation.LoadFromFile() method.
  • Loop through the slides in the presentation.
  • Save each slide to an image stream using ISlide.SaveAsImageByWH() method.
  • Save the image stream to a JPG, PNG or BMP file using Stream.Save() 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")

# Loop through the slides in the presentation
for i, slide in enumerate(presentation.Slides):
    # Specify the output file name
    fileName ="Output/ToImage_" + str(i) + ".png"
    # Save each slide to a PNG image with a size of 700 * 400 pixels
    slide1 = (ISlide)(slide)
    image = slide1.SaveAsImageByWH(700, 400)
    image.Save(fileName)
    image.Dispose()

presentation.Dispose()

Python: Convert PowerPoint to Images (PNG, JPG, BMP, SVG)

Convert PowerPoint Presentation to SVG Images in Python

To convert the slides in a PowerPoint presentation to SVG images, you can use the ISlide.SaveToSVG() method. The detailed steps are as follows:

  • Create a Presentation object.
  • Load a PowerPoint presentation using Presentation.LoadFromFile() method.
  • Enable the Presentation.IsNoteRetained property to retain notes when converting the presentation to SVG files.
  • Loop through the slides in the presentation.
  • Save each slide to an SVG stream using ISlide.SaveToSVG() method.
  • Save the SVG stream to an SVG file using Stream.Save() 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")

# Enable the IsNoteRetained property to retain notes when converting the presentation to SVG files
presentation.IsNoteRetained = True

# Loop through the slides in the presentation
for i, slide in enumerate(presentation.Slides):
    # Specify the output file name
    fileName = "SVG/ToSVG_" + str(i) + ".svg"
    # Save each slide to an SVG image
    slide1 = (ISlide)(slide)
    svgStream = slide1.SaveToSVG()
    svgStream.Save(fileName)

presentation.Dispose()

Python: Convert PowerPoint to Images (PNG, JPG, BMP, SVG)

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 in Excel provide a flexible way to add textual information or annotations to worksheets, charts, or other objects. They allow users to display explanatory text, labels, or comments that are not directly related to the data itself. In this guide, we will explore how to add, update, and delete textboxes 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

Add a Textbox to Excel in Python

A textbox can be added to the specified location of a worksheet using Worksheet.TextBoxes.AddTextBox() method. The TextBox object has a set of properties that allow you to set the text and formatting of the textbox. The detailed steps to create a textbox using Spire.XLS for Python are as follows.

  • Create a Workbook object.
  • Get a specific worksheet through Workbook.Worksheets[index] property.
  • Add a textbox to the worksheet at the specified location using Worksheet.TextBoxes.AddTextBox() method.
  • Set text of the textbox through TextBox.Text property.
  • Set formatting of the text through other properties under the TextBox object.
  • Save the workbook to an Excel file using Workbook.SaveToFile() method.
  • Python
from spire.xls import *
from spire.xls.common import *

# Create a Workbook object
workbook = Workbook()

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

# Add a textbox to the worksheet, specifying location and size
textBox = sheet.TextBoxes.AddTextBox(5, 3, 120, 300)

# Set fill color of the textbox
textBox.Fill.FillType = ShapeFillType.SolidColor
textBox.Fill.ForeKnownColor = ExcelColors.Gray25Percent

# Add text to the textbox and set the text alignment
textBox.Text = "This is a textbox in Excel."
textBox.HAlignment = CommentHAlignType.Center
textBox.VAlignment = CommentVAlignType.Center

# Set font for the text
font = workbook.CreateFont()
font.FontName = "Times New Roman"
font.Size = 18
font.IsBold = True
font.Color = Color.get_Blue()
richText = textBox.RichText
rt = RichText(richText)
rt.SetFont(0, len(textBox.Text) - 1, font)

# Save the workbook to an Excel file
workbook.SaveToFile('output/InsertTextbox.xlsx', ExcelVersion.Version2016)
workbook.Dispose()

Python: Add, Update, or Delete Textboxes in Excel

Update a Textbox in Excel in Python

A certain textbox can be accessed through Worksheet.TextBoxes[index] property and the text inside the box can be obtained or modified through TextBox.Text property. The following are the steps to update a textbox using Spire.XLS for Python.

  • Create a Workbook object.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Get a specific worksheet through Workbook.Worksheets[index] property.
  • Add a textbox to the worksheet at the specified location using Worksheet.TextBoxes.AddTextBox() method.
  • Reset text of the textbox through TextBox.Text property.
  • Save the workbook to a different Excel file using Workbook.SaveToFile() method.
  • Python
from spire.xls import *
from spire.xls.common import *

# Create a Workbook object
workbook = Workbook()

# Load an Excel file
workbook.LoadFromFile('C:\\Users\\Administrator\\Desktop\\Textbox.xlsx')

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

# Get the first textbox
tb = sheet.TextBoxes[0]

# Change the text of textbox
tb.Text = "The text in this textbox was changed."

# Save the workbook to a different Excel file
workbook.SaveToFile('output/UpdateTextbox.xlsx', ExcelVersion.Version2016)
workbook.Dispose()

Python: Add, Update, or Delete Textboxes in Excel

Delete a Textbox in Excel in Python

To remove a specific textbox, you use Worksheet.TextBox[index].Remove() method. The detailed steps are as follows.

  • Create a Workbook object.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Get a specific sheet through Workbook.Worksheets[index] property.
  • Remove a specific textbox by using Worksheet.TextBoxes[index].Remove() method.
  • Save the workbook to a different Excel file using Workbook.SaveToFile() method.
  • Python
from spire.xls import *
from spire.xls.common import *

# Create a Workbook object
workbook = Workbook()

# Load an Excel file
workbook.LoadFromFile('C:\\Users\\Administrator\\Desktop\\Textbox.xlsx')

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

# Remove the first textbox
sheet.TextBoxes[0].Remove()

# Save the workbook to a different Excel file
workbook.SaveToFile('output/RemoveTextbox.xlsx', ExcelVersion.Version2016)
workbook.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.

Page 23 of 26
page 23