Spire.Office Knowledgebase Page 54 | E-iceblue

Python: Split or Merge PDF Pages

2024-02-26 01:36:28 Written by Koohji

Modifying PDF documents to suit various usage scenarios is a common task for PDF document creators and managers. Among these operations, splitting and merging PDF pages can assist in reorganizing PDF content for printing, typesetting, etc. By using Python programs, developers can easily split one page from a PDF document to several pages or merge multiple PDF pages into a single page. This article will demonstrate how to use Spire.PDF for Python for splitting and merging PDF pages in Python programs.

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

Split One PDF Page into Several PDF Pages with Python

With Spire.PDF for Python, developers draw a PDF page on a new PDF page using the PdfPageBase.CreateTemplate().Draw(newPage PdfPageBase, PointF) method. When drawing, if the current new page cannot fully accommodate the content of the original page, a new page is automatically created, and the remaining content is drawn on it. Therefore, we can create a new PDF document and control the drawing result by specifying the page size to achieve specified division of PDF pages horizontally or vertically.

Here are the steps to vertically split a PDF page into two separate PDF pages:

  • Create an object of PdfDocument class and load a PDF document using PdfDocument.LoadFromFile() method.
  • Get the first page of the document using PdfDocument.Pages.get_Item() method.
  • Create a new PDF document by creating an object of PdfDocument class.
  • Set the margins of the new document to 0 through PdfDocument.PageSettings.Margins.All property.
  • Get the width and height of the retrieved page through PdfPageBase.Size.Width property and PdfPageBase.Size.Height property.
  • Set the width of the new PDF document to the same as the retrieved page through PdfDocument.PageSettings.Width property and its height to half of the retrieved page's height through PdfDocument.PageSettings.Height property.
  • Add a new page in the new document using PdfDocument.Pages.Add() method.
  • Draw the content of the retrieved page onto the new page using PdfPageBase.CreateTemplate().Draw() method.
  • Save the new document using PdfDocument.SaveToFile() method.
  • Python
from spire.pdf import *
from spire.pdf.common import *

# Create an object of PdfDocument class and load a PDF document
pdf = PdfDocument()
pdf.LoadFromFile("Sample.pdf")

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

# Create a new PDF document
newPdf = PdfDocument()

# Set the margins of the new PDF document to 0
newPdf.PageSettings.Margins.All = 0.0

# Get the width and height of the retrieved page
width = page.Size.Width
height = page.Size.Height

# Set the width of the new PDF document to the same as the retrieved page and its height to half of the retrieved page's height
newPdf.PageSettings.Width = width
newPdf.PageSettings.Height = height / 2

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

# Draw the content of the retrieved page onto the new page
page.CreateTemplate().Draw(newPage, PointF(0.0, 0.0))

# Save the new PDF document
newPdf.SaveToFile("output/SplitPDFPage.pdf")
pdf.Close()
newPdf.Close()

Python: Split or Merge PDF Pages

Merge Multiple PDF Pages into a Single Page with Python

Similarly, developers can merge PDF pages by drawing different pages on the same PDF page. It should be noted that the pages to be merged are preferably in the same width or height, otherwise it is necessary to take the maximum value to ensure correct drawing.

The detailed steps for merging two PDF pages into a single PDF page are as follows:

  • Create an object of PdfDocument class and load a PDF document using PdfDocument.LoadFromFile() method.
  • Get the first and second pages of the document using PdfDocument.Pages.get_Item() method.
  • Create a new PDF document by creating an object of PdfDocument class.
  • Set the margins of the new document to 0 through PdfDocument.PageSettings.Margins.All property.
  • Get the width and height of the two retrieved pages through PdfPageBase.Size.Width property and PdfPageBase.Size.Height property.
  • Set the width of the new PDF document to the same as the retrieved pages through PdfDocument.PageSettings.Width property and its height to the sum of the two retrieved pages' heights through PdfDocument.PageSettings.Height property.
  • Draw the content of the two retrieved pages onto the new page using PdfPageBase.CreateTemplate().Draw() method.
  • Save the new document using PdfDocument.SaveToFile() method.
  • Python
from spire.pdf import *
from spire.pdf.common import *

# Create an object of PdfDocument class and load a PDF document
pdf = PdfDocument()
pdf.LoadFromFile("Sample1.pdf")

# Get the first page and the second page of the document
page = pdf.Pages.get_Item(0)
page1 = pdf.Pages.get_Item(0)

# Create a new PDF document
newPdf = PdfDocument()

# Set the margins of the new PDF document to 0
newPdf.PageSettings.Margins.All = 0.0

# Set the page width of the new document to the same as the retrieved page
newPdf.PageSettings.Width = page.Size.Width

# Set the page height of the new document to the sum of the heights of the two retrieved pages
newPdf.PageSettings.Height = page.Size.Height + page1.Size.Height

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

# Draw the content of the retrieved pages onto the new page
page.CreateTemplate().Draw(newPage, PointF(0.0, 0.0))
page1.CreateTemplate().Draw(newPage, PointF(0.0, page.Size.Height))

# Save the new document
newPdf.SaveToFile("output/MergePDFPages.pdf")
pdf.Close()
newPdf.Close()

Python: Split or Merge PDF Pages

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.

Managing document properties in PowerPoint is an essential aspect of presentation creation. These properties serve as metadata that provides important information about the file, such as the author, subject, and keywords. By being able to add, retrieve, or remove document properties, users gain control over the organization and customization of their presentations. Whether it's adding relevant tags for easy categorization, accessing authorship details, or removing sensitive data, effectively managing document properties in PowerPoint ensures seamless collaboration and professionalism in your slide decks.

In this article, you will learn how to add, read, and remove document properties in a PowerPoint file in Python by using the Spire.Presentation for Python library.

Install Spire.Presentation for Python

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

pip install Spire.Presentation

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

Prerequisite Knowledge

Document properties can be divided into two types: standard document properties and custom document properties.

  • Standard document properties are pre-defined properties that are commonly used across various PowerPoint presentations. Some examples of standard document properties include title, author, subject, keywords and company. Standard document properties are useful for providing general information and metadata about the presentation.
  • Custom document properties are user-defined properties that allow you to add specific information to a PowerPoint presentation. Unlike standard document properties, custom properties are not predefined and can be tailored to suit your specific needs. Custom properties usually provide information relevant to your presentation that may not be covered by the default properties.

Spire.Presentation for Python offers the DocumentProperty class to work with both standard document properties and custom document properties. The standard document properties can be accessed using the properties like Title, Subject, Author, Manager, Company, etc. of the DocumentProperty class. To add or retrieve custom properties, you can use the set_Item() method and the GetPropertyName() method of the DocumentProperty class.

Add Document Properties to a PowerPoint File in Python

To add or change the standard document properties, you can assign values to the DocumentProperty.Title proerpty, DocumentProperty.Subject property and other similar properties. To add custom properties to a presentation, use the DocumentProperty.set_Item(name: str, value: SpireObject) method. The detailed steps are as follows.

  • Create a Presentation object.
  • Load a PowerPoint document using Presentation.LoadFromFile() method.
  • Get the DocumentProperty object.
  • Add standard document properties to the presentation by assigning values to the Title, Subject, Author, Manager, Company and Keywords properties of the object.
  • Add custom properties to the presentation using set_Item() of the object.
  • Save the presentation to a PPTX file using Presentation.SaveToFile() method.
  • Python
from spire.presentation.common import *
from spire.presentation import *

# Create a Presentation object
presentation = Presentation()

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

# Get the DocumentProperty object
documentProperty = presentation.DocumentProperty

# Set built-in document properties
documentProperty.Title = "Annual Sales Presentation"
documentProperty.Subject = "Company performance and sales strategy"
documentProperty.Author = "John Smith"
documentProperty.Manager = "Sarah Johnson"
documentProperty.Company = "E-iceblue Corporation"
documentProperty.Category = "Business"
documentProperty.Keywords = "sales, strategy, performance"
documentProperty.Comments = "Please review and provide feedback by Friday"

# Add custom document properties
documentProperty.set_Item("Document ID", Int32(12))
documentProperty.set_Item("Authorized by", String("Product Manager"))
documentProperty.set_Item("Authorized Date", DateTime(2024, 1, 10, 0, 0, 0, 0))

# Save to file
presentation.SaveToFile("output/Properties.pptx", FileFormat.Pptx2019)
presentation.Dispose()

Python: Add, Read, or Remove Document Properties in PowerPoint

Read Document Properties of a PowerPoint File in Python

The DocumentProperty.Title and the similar properties are not only used to set standard properties but can return the values of standard properties as well. Since the name of a custom property is not constant, we need to get the name using the DocumentProperty.GetPropertyName(index: int) method. And then, we're able to get the property's value using the DocumentProperty.get_Item(name: str) method.

The steps to read document properties of a PowerPoint file are as follows.

  • Create a Presentation object.
  • Load a PowerPoint document using Presentation.LoadFromFile() method.
  • Get the DocumentProperty object.
  • Get the standard document properties by using the Title, Subject, Author, Manager, Company, and Keywords properties of the object.
  • Get the count of the custom properties, and iterate through the custom properties.
  • Get the name of a specific custom property by its index using DocumentProperty.GetPropertyName() method.
  • Get the value of the property using DocumentProperty.get_Item() method.
  • Python
from spire.presentation.common import *
from spire.presentation import *

# Create a Presentation object
presentation = Presentation()

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

# Get the DocumentProperty object
documentProperty = presentation.DocumentProperty

# Get the built-in document properties
print("Title: " + documentProperty.Title)
print("Subject: " + documentProperty.Subject)
print("Author: " + documentProperty.Author)
print("Manager : " + documentProperty.Manager)
print("Company: " + documentProperty.Company)
print("Category: " + documentProperty.Category)
print("Keywords: " + documentProperty.Keywords)
print("Comments: " + documentProperty.Comments)

# Get the count of the custom document properties
count = documentProperty.Count

# Iterate through the custom properties
for i in range(count):

    # Get the name of a specific custom property
    customPropertyName = documentProperty.GetPropertyName(i)

    # Get the value of the custom property
    customPropertyValue = documentProperty.get_Item(customPropertyName)

    # Print the result
    print(customPropertyName + ": " + str(customPropertyValue))

Python: Add, Read, or Remove Document Properties in PowerPoint

Remove Document Properties from a PowerPoint File in Python

Removing a standard property means assigning an empty string to a property like DocumentProperty.Title. To remove the custom properties, Spire.Presentation provides the DocumentProperty.Remove(name: str) method. The following are the steps to remove document properties from a PowerPoint file in Python.

  • Create a Presentation object.
  • Load a PowerPoint document using Presentation.LoadFromFile() method.
  • Get the DocumentProperty object.
  • Set the Title, Subject, Author, Manager, Company, and Keywords properties of the object to empty strings.
  • Get the count of the custom properties.
  • Get the name of a specific custom property by its index using DocumentProperty.GetPropertyName() method.
  • Remove the custom property using DocumentProperty.Remove() method.
  • Save the presentation to a PPTX file using Presentation.SaveToFile() method.
  • Python
from spire.presentation.common import *
from spire.presentation import *

# Create a Presentation object
presentation = Presentation()

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

# Get the DocumentProperty object
documentProperty = presentation.DocumentProperty

# Set built-in document properties to empty strings
documentProperty.Title = ""
documentProperty.Subject = ""
documentProperty.Author = ""
documentProperty.Manager = ""
documentProperty.Company = ""
documentProperty.Category = ""
documentProperty.Keywords = ""
documentProperty.Comments = ""

# Get the count of the custom document properties
i = documentProperty.Count
while i > 0:

    # Get the name of a specific custom property
    customPropertyName = documentProperty.GetPropertyName(i - 1)

    # Remove the custom property
    documentProperty.Remove(customPropertyName)
    i = i - 1

# Save the presentation to a different pptx file
presentation.SaveToFile("Output/RemoveProperties.pptx",FileFormat.Pptx2019)

Python: Add, Read, or Remove Document Properties 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.

Images are an effective tool for conveying complex information. By inserting images into tables, you can enhance data presentation with charts, graphs, diagrams, illustrations, and more. This not only enables readers to easily comprehend the information being presented but also adds visual appeal to your document. In certain cases, you may also come across situations where you need to extract images from tables for various purposes. For example, you might want to reuse an image in a presentation, website, or another document. Extracting images allows you to repurpose them, streamlining your content creation process and increasing efficiency. In this article, we will explore how to insert and extract images in Word tables in Python using Spire.Doc for Python.

Install Spire.Doc for Python

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

pip install Spire.Doc

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

Insert Images into a Word Table in Python

Spire.Doc for Python provides the TableCell.Paragraphs[index].AppendPicture() method to add an image to a specific table cell. The detailed steps are as follows.

  • Create an object of the Document class.
  • Load a Word document using the Document.LoadFromFile() method.
  • Get a specific section in the document using the Document.Sections[index] property.
  • Get a specific table in the section using the Section.Tables[index] property.
  • Access a specific cell in the table using the Table.Row[index].Cells[index] property.
  • Add an image to the cell using the TableCell.Paragraphs[index].AppendPicture() method and set the image width and height.
  • Save the result document using the Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create an object of the Document class
doc = Document()
# Load a Word document
doc.LoadFromFile("Table2.docx")

# Get the first section
section = doc.Sections[0]

# Get the first table in the section
table = section.Tables[0]

# Add an image to the 3rd cell of the second row in the table
cell = table.Rows[1].Cells[2]
picture = cell.Paragraphs[0].AppendPicture("doc.png")
# Set image width and height
picture.Width = 100
picture.Height = 100

# Add an image to the 3rd cell of the 3rd row in the table
cell = table.Rows[2].Cells[2]
picture = cell.Paragraphs[0].AppendPicture("xls.png")
# Set image width and height
picture.Width = 100
picture.Height = 100

# Save the result document
doc.SaveToFile("AddImagesToTable.docx", FileFormat.Docx2013)
doc.Close()

Python: Insert or Extract Images in Word Tables

Extract Images from a Word Table in Python

To extract images from a Word table, you need to iterate through all objects in the table and identify the ones of the DocPicture type. Once the DocPicture objects are found, you can access their image bytes using the DocPicture.ImageBytes property, and then save the image bytes to image files. The detailed steps are as follows.

  • Create an object of the Document class.
  • Load a Word document using the Document.LoadFromFile() method.
  • Get a specific section in the document using the Document.Sections[index] property.
  • Get a specific table in the section using the Section.Tables[index] property.
  • Create a list to store the extracted image data.
  • Iterate through all rows in the table.
  • Iterate through all cells in each row.
  • Iterate through all paragraphs in each cell.
  • Iterate through all child objects in each paragraph.
  • Check if the current child object is of DocPicture type.
  • Get the image bytes of the DocPicture object using the DocPicture.ImageBytes property and append them to the list.
  • Save the image bytes in the list to image files.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create an object of the Document class
doc = Document()
# Load a Word document
doc.LoadFromFile("AddImagesToTable.docx")

# Get the first section
section = doc.Sections[0]

# Get the first table in the section
table = section.Tables[0]

# Create a list to store image bytes
image_data = []

# Iterate through all rows in the table
for i in range(table.Rows.Count):
    row = table.Rows[i]
    # Iterate through all cells in each row
    for j in range(row.Cells.Count):
        cell = row.Cells[j]
        # Iterate through all paragraphs in each cell
        for k in range(cell.Paragraphs.Count):
            paragraph = cell.Paragraphs[k]
            # Iterate through all child objects in each paragraph
            for o in range(paragraph.ChildObjects.Count):
                child_object = paragraph.ChildObjects[o]
                # Check if the current child object is of DocPicture type
                if isinstance(child_object, DocPicture):
                    picture = child_object
                    # Get the image bytes
                    bytes = picture.ImageBytes
                    # Append the image bytes to the list
                    image_data.append(bytes)

# Save the image bytes in the list to image files
for index, item in enumerate(image_data):
    image_Name = f"Images/Image-{index}.png"
    with open(image_Name, 'wb') as imageFile:
        imageFile.write(item)

doc.Close()

Python: Insert or Extract Images in Word Tables

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 54

Coupon Code Copied!

Christmas Sale

Celebrate the season with exclusive savings

Save 10% Sitewide

Use Code:

View Campaign Details