Python: Insert, Retrieve, Reorder, and Remove Slides in PowerPoint Sections
PowerPoint presentations are a powerful tool for presenting information in an organized and engaging manner. To further enhance the organization of slides, PowerPoint allows users to group slides into sections. This feature makes navigating and managing large presentations much easier. In this article, we'll show you how to manage slides within PowerPoint sections in Python using Spire.Presentation for Python. Specifically, we'll cover how to add, retrieve, reorder, and remove slides in these sections.
- Insert Slides into a PowerPoint Section in Python
- Retrieve Slides from a PowerPoint Section in Python
- Reorder Slides in a PowerPoint Section in Python
- Remove Slides from a PowerPoint Section in 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
Insert Slides into a PowerPoint Section in Python
Inserting slides is essential when you want to introduce new content to a section. Using Spire.Presentation for Python, you can quickly insert a slide into a section with the Section.Insert() method. The detailed steps are as follows.
- Create an instance of the Presentation class.
- Load a PowerPoint presentation using the Presentation.LoadFromFile() method.
- Get a specific section through its index (0-based) using the Presentation.SectionList(index) property.
- Add a new slide to the presentation, then insert it into the section using the Section.Insert() method.
- Remove the added slide from the presentation.
- Save the resulting presentation using the Presentation.SaveToFile() method.
- Python
from spire.presentation import *
# Create an instance of the Presentation class
presentation = Presentation()
# Load a PowerPoint presentation
presentation.LoadFromFile("Example.pptx")
# Access the first section
first_section = presentation.SectionList.get_Item(0)
# Add a new slide to the presentation and insert it at the start of the section
slide = presentation.Slides.Append()
first_section.Insert(0, slide)
# Remove the added slide from the presentation
presentation.Slides.Remove(slide)
# Save the modified presentation
presentation.SaveToFile("InsertSlidesInSection.pptx", FileFormat.Pptx2016)
# Close the Presentation object
presentation.Dispose()

Retrieve Slides from a PowerPoint Section in Python
Retrieving slides from a specific section allows you to focus on a smaller group of slides for tasks such as reordering or applying custom formatting. Using the Section.GetSlides() method in Spire.Presentation for Python, you can easily access all the slides in a particular section. The detailed steps are as follows.
- Create an instance of the Presentation class.
- Load a PowerPoint presentation using the Presentation.LoadFromFile() method.
- Get a specific section through its index (0-based) using the Presentation.SectionList(index) property.
- Retrieve the slides within the section using the Section.GetSlides() method.
- Iterate through the retrieved slides and get the slide number (1-based) of each slide.
- Python
from spire.presentation import *
# Create an instance of the Presentation class
presentation = Presentation()
# Load a PowerPoint presentation
presentation.LoadFromFile("Example.pptx")
# Retrieve the slides in the 3rd section
section = presentation.SectionList.get_Item(2)
slides = section.GetSlides()
output_content = "The slide numbers in this section are:\n"
# Get the slide number of each slide in the section
for slide in slides:
output_content += str(slide.SlideNumber) + " "
# Save the slide number to a text file
with open("slide_numbers.txt", "w") as file:
file.write(output_content)

Reorder Slides in a PowerPoint Section in Python
Reordering slides is important to ensure related content is in the right order. Spire.Presentation for Python offers the Section.Move() method, which allows you to move a slide to a new position within a section. The detailed steps are as follows.
- Create an instance of the Presentation class.
- Load a PowerPoint presentation using the Presentation.LoadFromFile() method.
- Get a specific section through its index (0-based) using the Presentation.SectionList(index) property.
- Move a specific slide in the section to another position using the Section.Move() method.
- Save the resulting presentation using the Presentation.SaveToFile() method.
- Python
from spire.presentation import *
# Create an instance of the Presentation class
presentation = Presentation()
# Load a PowerPoint presentation
presentation.LoadFromFile("Example.pptx")
# Access the 3rd section
section = presentation.SectionList.get_Item(2)
# Retrieve the slides in the section
slides = section.GetSlides()
# Move the 1st slide in the section to the specified position
section.Move(2, slides[0])
# Save the modified presentation
presentation.SaveToFile("ReorderSlidesInSection.pptx", FileFormat.Pptx2016)
# Close the Presentation object
presentation.Dispose()

Remove Slides from a PowerPoint Section in Python
Removing slides from a section streamlines your presentation, particularly when some slides become outdated or unnecessary. With Spire.Presentation for Python, you can easily remove a single slide or multiple slides from a section using the Section.RemoveAt() or Section.RemoveRange() method. The detailed steps are as follows.
- Create an instance of the Presentation class.
- Load a PowerPoint presentation using the Presentation.LoadFromFile() method.
- Get a specific section through its index (0-based) using the Presentation.SectionList(index) property.
- Remove a specific slide or a range of slides from the presentation using the Section.RemoveAt() or Section.RemoveRange() method.
- Save the resulting presentation using the Presentation.SaveToFile() method.
- Python
from spire.presentation import *
# Create an instance of the Presentation class
presentation = Presentation()
# Load a PowerPoint presentation
presentation.LoadFromFile("Example.pptx")
# Access the 3rd section
section = presentation.SectionList.get_Item(2)
# Remove the first slide from the section
section.RemoveAt(0)
# Or remove a range of slides from the section
# section.RemoveRange(0, 2)
# Save the modified presentation
presentation.SaveToFile("RemoveSlidesInSection.pptx", FileFormat.Pptx2016)
# Close the Presentation object
presentation.Dispose()
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
C#: Create Actions in PDF Documents
Enhancing the interactivity of PDF files is a crucial aspect of document management and user engagement. Creating actions within PDFs using C# in the .NET framework allows developers to add dynamic elements such as file links, web links, and audio that can execute various functions like navigating to different pages, launching external applications, or playing background music, which improves the user experience by making PDFs more functional and engaging. This article demonstrates how to use the Spire.PDF for .NET library to create actions in PDF documents with C#.
- General Steps for Adding Actions to PDF with C#
- Create Navigation Actions in PDF with C#
- Create File Launch Actions in PDF with C#
- Create Sound Actions in PDF with C#
- Create Web Link Actions in PDF with C#
- Create JavaScript Actions in PDF with C#
Install Spire.PDF for .NET
To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.PDF
General Steps for Adding Actions to PDF with C#
Adding actions to a PDF using C# involves integrating interactive elements that enhance user experience, such as navigation buttons, file links, web links, or sound triggers. With the Spire.PDF for .NET library, developers can create various actions in PDF documents with C# code. Below is a table of the classes for commonly used actions and their descriptions:
| Class | Decryption |
| PdfGoToAction | Represents an action that navigates to a destination within the current document. |
| PdfLaunchAction | Represents an action that opens a file. |
| PdfSoundAction | Represents an action that plays a sound. |
| PdfJavaScriptAction | Represents an action that executes JavaScript code in a PDF document. |
| PdfUriAction | Represents an action that resolves a Uniform Resource Identifier (URI). |
| PdfGoToAction | Represents an action that navigates to a destination within the current document. |
For more action classes and their descriptions, refer to Spire.PDF for .NET action API references.
Actions can be added to PDF documents in two primary ways:
1. Using Action Annotations
This method involves creating an action and linking it to an annotation on the page. The action is displayed and triggered when the annotation is clicked.
General Steps:
- Create an instance of PdfDocument class and load a PDF document using PdfDocument.LoadFromFile() method.
- Get a page using PdfDocument.Pages[] property.
- Create an instance of the class that represents the action and set the action properties.
- Create an instance of PdfLinkAnnotation class in a rectangular area on the page using the action.
- Add the cue word for the action to the page (optional).
- Add the action annotation to the page using PdfPageBase.AnnotationsV2.Add() method.
- Save the result document using PdfDocument.SaveToFile() method.
2. Assigning Actions to Document Events
Actions can also be assigned to document-level events such as opening, closing, or printing the document. These actions are triggered automatically when the specified events occur.
General Steps:
- Create an instance of PdfDocument class and load a PDF document using PdfDocument.LoadFromFile() method.
- Create an instance of the class that represents the action and set the action properties.
- Assign the action to a document event using the following properties:
- PdfDocument.AfterOpenAction
- PdfDocument.AfterSaveAction
- PdfDocument.AfterPrintAction
- PdfDocument.BeforeCloseAction
- PdfDocument.BeforeSaveAction
- PdfDocument.BeforePrintAction
- Save the result document using PdfDocument.SaveToFile() method.
Create Navigation Actions in PDF with C#
Navigation actions can be created using the PdfGoToAction class, which defines navigation within the document to a specified destination. To achieve this, developers can create a PdfXYZExplicitDestination object and pass it as a parameter to a PdfGoToAction instance.
The following is a code example of adding a navigation action to a PDF:
- C#
using Spire.Pdf;
using Spire.Pdf.Actions;
using Spire.Pdf.Interactive.Annotations;
using Spire.Pdf.Destinations;
using Spire.Pdf.Graphics;
using System.Drawing;
namespace AddNavigationButtonPDF
{
class Program
{
static void Main(string[] args)
{
// Create an instance of PdfDocument
PdfDocument pdf = new PdfDocument();
// Load a PDF file
pdf.LoadFromFile("Sample.pdf");
// Create a PdfXYZExplicitDestination instance and set the destination
PdfXYZExplicitDestination destination = new PdfXYZExplicitDestination(pdf.Pages[1], 0f, 0f, 0.8f);
// Create a PdfGoToAction based on the destination
PdfGoToAction action = new PdfGoToAction(destination);
// Create a rectangle and draw it on the first page
RectangleF rect = new RectangleF(70, pdf.PageSettings.Size.Height - 120, 140, 20);
pdf.Pages[0].Canvas.DrawRectangle(PdfBrushes.LightGray, rect);
// Draw cue words on the rectangle
PdfFont font = new PdfFont(PdfFontFamily.TimesRoman, 14);
PdfStringFormat stringFormat = new PdfStringFormat(PdfTextAlignment.Center);
pdf.Pages[0].Canvas.DrawString("To Page 2", font, PdfBrushes.Green, rect, stringFormat);
// Create a PdfLinkAnnotation instance based on the rectangle and the action
PdfLinkAnnotation actionAnnotation = new PdfLinkAnnotation(pdf.Pages[0], rect, action);
// Add the action annotation to the first page
pdf.Pages[0].AnnotationsV2.Add(actionAnnotation);
// Save the document
pdf.SaveToFile("output/NavigationButton.pdf");
pdf.Close();
}
}
}

Create File Launch Actions in PDF with C#
The PdfLaunchAction class defines a file open action in a PDF that enables users to open a specific file by clicking a button embedded on a PDF page. When implementing this action, developers can set the file path (absolute or relative) and decide whether the file should open in a new window. Here is a code example for adding a file launch action in a PDF document:
- C#
using Spire.Pdf;
using Spire.Pdf.Actions;
using Spire.Pdf.Interactive.Annotations;
using Spire.Pdf.Graphics;
using System.Drawing;
namespace AddFileLaunchActionPDF
{
class Program
{
static void Main(string[] args)
{
// Create an instance of PdfDocument
PdfDocument pdf = new PdfDocument();
// Load a PDF file
pdf.LoadFromFile("Sample.pdf");
// Get the first page
PdfPageBase page = pdf.Pages[0];
// Draw a rectangle on the page
RectangleF rect = new RectangleF(50, 50, 180, 20);
page.Canvas.DrawRectangle(PdfBrushes.LightGray, rect);
// Draw the cue words in the rectangle
PdfFont font = new PdfFont(PdfFontFamily.TimesRoman, 14);
PdfStringFormat stringFormat = new PdfStringFormat(PdfTextAlignment.Center);
pdf.Pages[0].Canvas.DrawString("Click to launch Sample2", font, PdfBrushes.Green, rect, stringFormat);
// Create a PdfLaunchAction instance
PdfLaunchAction action = new PdfLaunchAction("C:/Sample2.pdf", PdfFilePathType.Absolute);
// Set the launch mode to open in new window
action.NewWindow = true;
// Create a PdfLinkAnnotation instance based on the rectangle and the launch action
PdfLinkAnnotation actionAnnotation = new PdfLinkAnnotation(page, rect, action);
// Add the action annotation to the first page
page.AnnotationsV2.Add(actionAnnotation);
// Save the document
pdf.SaveToFile("output/LaunchAction.pdf");
pdf.Close();
}
}
}

Create Sound Actions in PDF with C#
Developers can embed audio as an action in PDF documents with the PdfSoundAction class, enabling the audio to play in response to specific triggers, such as opening the file or clicking a button. Below is a code example for creating a sound action in a PDF document:
- C#
using Spire.Pdf;
using Spire.Pdf.Actions;
using Spire.Pdf.Interactive.Annotations;
using Spire.Pdf.Graphics;
using System.Drawing;
namespace AddSoundActionPDF
{
class Program
{
static void Main(string[] args)
{
// Create an instance of PdfDocument
PdfDocument pdf = new PdfDocument();
// Load a PDF file
pdf.LoadFromFile("Sample.pdf");
// Get the first page
PdfPageBase page = pdf.Pages[0];
// Draw the cue image on the page
PdfImage image = PdfImage.FromFile("Sound.png");
page.Canvas.DrawImage(image, new PointF(30, 30));
// Create a PdfSoundAction instance and set its property
PdfSoundAction action = new PdfSoundAction("Wave.wav");
// Set the sound parameters
action.Sound.Bits = 16;
action.Sound.Channels = PdfSoundChannels.Stereo;
action.Sound.Encoding = PdfSoundEncoding.Signed;
action.Sound.Rate = 44100;
// Set the play options
action.Volume = 0;
action.Repeat = true;
action.Mix = true;
action.Synchronous = true;
// Create a PdfLinkAnnotation instance using the sound action at the location of the cue image
RectangleF rect = new RectangleF(30, 30, image.Width, image.Height);
PdfLinkAnnotation actionAnnotation = new PdfLinkAnnotation(page, rect, action);
// Add the action annotation to the first page
page.AnnotationsV2.Add(actionAnnotation);
// Set the sound action to play after the document is opened
pdf.AfterOpenAction = action;
// Save the document
pdf.SaveToFile("output/SoundAction.pdf");
pdf.Close();
}
}
}

Create Web Link Actions in PDF with C#
Developers can use the PdfURIAction class to create a web link action in PDF documents, allowing users to open a web link when performing specific actions, such as clicking a button. Below is a code example for creating a web link action in a PDF document:
- C#
using Spire.Pdf;
using Spire.Pdf.Actions;
using Spire.Pdf.Interactive.Annotations;
using Spire.Pdf.Graphics;
using System.Drawing;
namespace AddUriActionPDF
{
class Program
{
static void Main(string[] args)
{
// Create an instance of PdfDocument
PdfDocument pdf = new PdfDocument();
// Load a PDF file
pdf.LoadFromFile("Sample.pdf");
// Get the first page
PdfPageBase page = pdf.Pages[0];
// Draw a rectangle on the page
RectangleF rect = new RectangleF(30, 30, 120, 20);
page.Canvas.DrawRectangle(PdfBrushes.LightGray, rect);
// Draw the cue words in the rectangle
PdfFont font = new PdfFont(PdfFontFamily.TimesRoman, 14);
PdfStringFormat stringFormat = new PdfStringFormat(PdfTextAlignment.Center);
page.Canvas.DrawString("Go to Google Search", font, PdfBrushes.LightSkyBlue, rect);
// Create a PdfURIAction instance and set its property
PdfURIAction action = new PdfURIAction("https://www.google.com/");
// Create a PdfLinkAnnotation instance using the web link action and the rectangle
PdfLinkAnnotation actionAnnotation = new PdfLinkAnnotation(page, rect, action);
// Add the action annotation to the first page
page.AnnotationsV2.Add(actionAnnotation);
// Save the document
pdf.SaveToFile("output/WebLinkAction.pdf");
pdf.Close();
}
}
}

Create JavaScript Actions in PDF with C#
The PdfJavaScriptAction represents a JavaScript action in PDF, which allows developers to create complex interactions such as form validations, data calculations, and custom user interfaces. Below is a code example for adding a simple JavaScript action to a PDF document with C#:
- C#
using Spire.Pdf;
using Spire.Pdf.Actions;
namespace AddJavaScriptActionPDF
{
class Program
{
static void Main(string[] args)
{
// Create a PdfDocument instance
PdfDocument pdf = new PdfDocument();
// Load a PDF file
pdf.LoadFromFile("Sample.pdf");
// Define JavaScript code
var jsCode =
"app.alert({" +
" cMsg: 'Welcome to the article about the Evolution and Advantages of LCD Screens!\\n\\nThis article explores the history and benefits of LCD technology, including its impact on visual experiences across various devices.', " +
" nIcon: 3, " +
" cTitle: 'Document Introduction'" +
"});";
// Create a PdfJavaScriptAction instance using the JavaScript code
PdfJavaScriptAction action = new PdfJavaScriptAction(jsCode);
// Set the action to be executed when the PDF document is launched
pdf.AfterOpenAction = action;
// Save the document
pdf.SaveToFile("output/PDFJavaScriptAction.pdf");
pdf.Close();
}
}
}

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: Extract Annotations from PDF
Annotations in PDF documents play a crucial role in enhancing collaboration, emphasizing key points, or providing additional context. Extracting annotations is essential for efficiently analyzing PDF content, but manual extraction can be tedious. This guide demonstrates how to extract annotations from PDF with Python using Spire.PDF for Python, providing a faster and more flexible solution to access important information.
- Extract Specified Annotations from PDF Documents
- Extract All Annotations from a PDF Page
- Extract All Annotations from PDF Files
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 it, please refer to this tutorial: How to Install Spire.PDF for Python on Windows.
Extract Specified Annotations from PDF Documents
Although Adobe Acrobat offers a built-in one-click annotation extraction feature, it lacks flexibility when handling specific annotations. If you only need to extract one or a few annotations, you must manually locate and copy them, which can be inefficient, especially when working with PDFs containing multiple annotations. Spire.PDF (short for Spire.PDF for Python), however, provides the PdfAnnotationCollection.get_item() method, enabling targeted extraction of specific annotations, making PDF annotation management more flexible and efficient.
Steps to extract specified annotations from PDF:
- Create an object of PdfDocument class.
- Load a PDF document from the local storage with PdfDocument.LoadFromFile() method.
- Get a page using PdfDocument.Pages[] property, and access the annotations collection with PdfPageBase.AnnotationsWidget property.
- Create a list to store annotation information.
- Access the specified annotation using PdfAnnotationCollection.get_Item() method.
- Append annotation details to the list.
- Save the list as a Text file.
Here is the code example of exporting the first annotation on the third page:
- Python
from spire.pdf.common import *
from spire.pdf import *
# Create a new PDF document
pdf = PdfDocument()
# Load the file from disk
pdf.LoadFromFile( "Sample.pdf")
# Get the third page
page = doc.Pages.get_Item(2)
# Access the annotations on the page
annotations = page.AnnotationsWidget
# Create a list to save information of annotations
sb = []
# Access the first annotation on the page
annotation = annotations.get_Item(0)
# Append the annotation details to the list
sb.append("Annotation information: ")
sb.append("Text: " + annotation.Text)
modifiedDate = annotation.ModifiedDate.ToString()
sb.append("ModifiedDate: " + modifiedDate)
# Save the list as a Text file
with open("GetSpecificAnnotation.txt", "w", encoding="utf-8") as file:
file.write("\n".join(sb))
# Close the PDF file
pdf.Close()

Extract All Annotations from a PDF Page
To export all annotations from a specified PDF page, you can still use the PdfPageBase.AnnotationsWidget property along with the PdfAnnotationCollection.get_item() method. However, you will need to iterate through all the annotations on the page to ensure none are missed. Below are the steps and code examples to guide you through the process.
Steps to extract annotations from PDF pages:
- Create a PdfDocument instance.
- Read a PDF document from the local storage with PdfDocument.LoadFromFile() method.
- Access the annotation collection on the specified page using PdfDocument.Pages.AnnotationsWidget property.
- Create a list to store annotation information.
- Loop through annotations on a certain page.
- Retrieve each annotation using PdfAnnotationCollection.get_Item() method.
- Add annotation details to the list.
- Save the list as a Text file.
Below is the code example of extracting all annotations on the second page:
- Python
from spire.pdf.common import *
from spire.pdf import *
# Create a new PDF document
pdf = PdfDocument()
# Load the file from disk
pdf.LoadFromFile("Sample.pdf")
# Get all annotations from the second page
annotations = pdf.Pages.get_Item(1).AnnotationsWidget
# Create a list to maintain annotation details
sb = []
# Loop through annotations on the page
if annotations.Count > 0:
for i in range(annotations.Count):
# Get the current annotation
annotation = annotations.get_Item(i)
# Get the annotation details
if isinstance(annotation, PdfPopupAnnotationWidget):
continue
sb.append("Annotation information: ")
sb.append("Text: " + annotation.Text)
modifiedDate = annotation.ModifiedDate.ToString()
sb.append("ModifiedDate: " + modifiedDate)
# Save annotations as a Text file
with open("GetAllAnnotationsFromPage.txt", "w", encoding="utf-8") as file:
file.write("\n".join(sb))
# Release resources
pdf.Close()

Extract All Annotations from PDF Files
The final section of this guide illustrates how to extract all annotations from a PDF document using Python. The process is similar to exporting annotations from a single page but involves iterating through each page, traversing all annotations, and accessing their details. Finally, the extracted annotation details are saved to a text file for further use. Let’s take a closer look at the detailed steps.
Steps to extract all annotations from a PDF document:
- Create an instance of PdfDocument class.
- Read a PDF document from the disk with PdfDocument.LoadFromFile() method.
- Initialize a list to store annotation information.
- Loop through all pages and access the annotation collection with PdfDocument.Pages.AnnotationsWidget property.
- Iterate each annotation in the collection and get annotations using PdfAnnotationCollection.get_item() method.
- Append annotation details to the list.
- Output the list as a Text file.
Here is an example of exporting all annotations from a PDF file:
- Python
from spire.pdf.common import *
from spire.pdf import *
# Create a new PDF document
pdf = PdfDocument()
# Load the file from disk
pdf.LoadFromFile("Sample.pdf")
# Create a list to save annotation details
sb = []
# Iterate through all pages in the PDF document
for pageIndex in range(pdf.Pages.Count):
sb.append(f"Page {pageIndex + 1}:")
# Access the annotation collection of the current page
annotations = pdf.Pages.get_Item(pageIndex).AnnotationsWidget
# Loop through annotations in the collection
if annotations.Count > 0:
for i in range(annotations.Count):
# Get the annotations of the current page
annotation = annotations.get_Item(i)
# Skip invalid annotations (empty text and default date)
if not annotation.Text.strip() and annotation.ModifiedDate.ToString() == "0001/1/1 0:00:00":
continue
# Extract annotation information
sb.append("Annotation information: ")
sb.append("Text: " + (annotation.Text.strip() or "N/A"))
modifiedDate = annotation.ModifiedDate.ToString()
sb.append("ModifiedDate: " + modifiedDate)
else:
sb.append("No annotations found.")
# Add a blank line after each page
sb.append("")
# Save all annotations to a file
with open("GetAllAnnotationsFromDocument.txt", "w", encoding="utf-8") as file:
file.write("\n".join(sb))
# Close the PDF document
pdf.Close()

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Python: Split PowerPoint Presentations
Splitting a PowerPoint presentation into smaller files or individual sections can be useful in various situations. For instance, when collaborating with a team, each member may only need a specific section of the presentation to work on. Additionally, breaking a large presentation into smaller parts can simplify sharing over email or uploading to platforms with file size restrictions. In this article, we'll show you how to split PowerPoint presentations by slides, slide ranges, and sections in Python using Spire.Presentation for Python.
- Split PowerPoint Presentations by Slides in Python
- Split PowerPoint Presentations by Slide Ranges in Python
- Split PowerPoint Presentations by Sections in Python
Install Spire.Presentation for Python
This scenario requires Spire.Presentation for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.
pip install Spire.Presentation
If you are unsure how to install, please refer to this tutorial: How to Install Spire.Presentation for Python on Windows
Split PowerPoint Presentations by Slides in Python
Developers can use Spire.Presentation for Python to split a PowerPoint presentation into individual slides by iterating through the slides in the presentation and adding each slide to a new presentation. The detailed steps are as follows.
- Create an instance of the Presentation class.
- Load a PowerPoint presentation using the Presentation.LoadFromFile() method.
- Iterate through all slides in the presentation:
- Access the current slide through the Presentation.Slides[index] property.
- Create a new PowerPoint presentation using the Presentation class and remove its default slide using the Presentation.Slides.RemoveAt(0) method.
- Append the current slide to the new presentation using the Presentation.Slides.AppendBySlide() method.
- Save the new presentation as a file using the ISlide.SaveToFile() method.
- Python
from spire.presentation.common import *
from spire.presentation import *
# Create an instance of the Presentation class
presentation = Presentation()
# Load a PowerPoint presentation
presentation.LoadFromFile("Sample.pptx")
# Iterate through all slides in the presentation
for i in range(presentation.Slides.Count):
# Get the current slide
slide = presentation.Slides[i]
# Create a new PowerPoint presentation and remove its default slide
newPresentation = Presentation()
newPresentation.Slides.RemoveAt(0)
# Append the current slide to the new presentation
newPresentation.Slides.AppendBySlide(slide)
# Save the new presentation as a file
newPresentation.SaveToFile(f"output/Presentations/Slide-{i + 1}.pptx", FileFormat.Pptx2013)
newPresentation.Dispose()
presentation.Dispose()

Split PowerPoint Presentations by Slide Ranges in Python
Apart from splitting a PowerPoint presentation into individual slides, developers can also divide it into specific ranges of slides by adding the desired slides to new presentations. The detailed steps are as follows.
- Create an instance of the Presentation class.
- Load a PowerPoint presentation using the Presentation.LoadFromFile() method.
- Create new PowerPoint presentations using the Presentation class and remove the default slides within them using the Presentation.Slides.RemoveAt(0) method.
- Append specified ranges of slides to the new presentations using the Presentation.Slides.AppendBySlide() method.
- Save the new presentations as files using the Presentation.SaveToFile() method.
- Python
from spire.presentation.common import *
from spire.presentation import *
# Create an instance of the Presentation class
presentation = Presentation()
# Load a PowerPoint presentation
presentation.LoadFromFile("Sample.pptx")
# Create two new PowerPoint presentations and remove their default slides
presentation1 = Presentation()
presentation2 = Presentation()
presentation1.Slides.RemoveAt(0)
presentation2.Slides.RemoveAt(0)
# Append slides 1-3 to the first new presentation
for i in range(3):
presentation1.Slides.AppendBySlide(presentation.Slides[i])
# Append the remaining slides to the second new presentation
for i in range(3, presentation.Slides.Count):
presentation2.Slides.AppendBySlide(presentation.Slides[i])
# Save the new presentations as files
presentation1.SaveToFile("output/Presentations/SlideRange1.pptx", FileFormat.Pptx2013)
presentation2.SaveToFile("output/Presentations/SlideRange2.pptx", FileFormat.Pptx2013)
presentation1.Dispose()
presentation2.Dispose()
presentation.Dispose()

Split PowerPoint Presentations by Sections in Python
Sections in PowerPoint are often used to organize slides into manageable groups. With Spire.Presentation for Python, developers can split a PowerPoint presentation into sections by iterating through the sections in the presentation and adding the slides within each section to a new presentation. The detailed steps are as follows.
- Create an instance of the Presentation class.
- Load a PowerPoint presentation using the Presentation.LoadFromFile() method.
- Iterate through all sections in the presentation:
- Access the current section through the Presentation.SectionList[] property.
- Create a new PowerPoint presentation using the Presentation class and remove its default slide using the Presentation.Slides.RemoveAt(0) method.
- Add a section to the new presentation with the same name using the Presentation.SectionList.Append() method.
- Retrieve the slides of the current section using the Section.GetSlides() method.
- Iterate through the retrieved slides and add them to the section of the new presentation using the Section.Insert() method.
- Save the new presentation as a file using the Presentation.SaveToFile() method.
- Python
from spire.presentation.common import *
from spire.presentation import *
# Create an instance of the Presentation class
presentation = Presentation()
# Load a PowerPoint presentation
presentation.LoadFromFile("Sample.pptx")
# Iterate through all sections
for i in range(presentation.SectionList.Count):
# Get the current section
section = presentation.SectionList.get_Item(0)
# Create a new PowerPoint presentation and remove its default slide
newPresentation = Presentation()
newPresentation.Slides.RemoveAt(0)
# Add a section to the new presentation
newSection = newPresentation.SectionList.Append(section.Name)
# Retrieve the slides of the current section
slides = section.GetSlides()
# Insert each retrieved slide into the section of the new presentation
for slide_index, slide in enumerate(slides):
newSection.Insert(slide_index, slide)
# Save the new presentation as a file
newPresentation.SaveToFile(f"output/Presentations/Section-{i + 1}.pptx", FileFormat.Pptx2019)
newPresentation.Dispose()
presentation.Dispose()

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Python: Convert Excel Data to Word Table with Formatting
Excel is ideal for data calculations, analysis, and organization, while Word shines at creating polished, well-formatted documents and reports. Transferring data from Excel to Word is often necessary for professionals preparing reports or presentations, as it allows for advanced formatting options that enhance readability and create a more professional look. In this guide, you will learn how to convert data in an Excel sheet to a Word table with formatting in Python using Spire.Office for Python.
Install Spire.Office for Python
This scenario requires Spire.Office for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.
pip install Spire.Office
Convert Excel Data to Word Table with Formatting in Python
This process uses two libraries in the Spire.Office for Python package. They’re Spire.XLS for Python and Spire.Doc for Python. The former is used to read data and formatting from an Excel worksheet, and the latter is used to create a Word document and write data, including formatting, into a table. To make this code example easy to understand, we have defined the following two custom methods that handle specific tasks:
- MergeCells() - Merge the corresponding cells in the Word table based on the merged cells in the Excel sheet.
- CopyStyle() - Copy various cell styles from the Excel worksheet to the Word table, including font style, background color, and text alignment.
The following steps demonstrate how to convert data from an Excel sheet to a Word table with formatting using Spire.Office for Python.
- Create an object of the Workbook class and load a sample Excel file using the Workbook.LoadFromFile() method.
- Get a specific worksheet through the Workbook.Worksheets[index] property.
- Create a new Word document using the Document class, and add a section to it.
- Add a table to the Word document using the Section.AddTable() method.
- Detect the merged cells in the worksheet and merge the corresponding cells in the Word tale using the custom method MergeCells().
- Iterate through the cells in the worksheet, read the data of the cells through the CellRange.Value property and add the data to Word table cells using the TableCell.AddParagraph().AppendText() method.
- Copy the cell styles from the Excel worksheet to the Word table using the custom method CopyStyle().
- Save the Word document to a file using the Document.SaveToFile() method.
- Python
from spire.xls import *
from spire.doc import *
def MergeCells(sheet, table):
"""Merge cells in the Word table based on merged cells in the Excel sheet."""
if sheet.HasMergedCells:
ranges = sheet.MergedCells
for i in range(len(ranges)):
startRow = ranges[i].Row
startColumn = ranges[i].Column
rowCount = ranges[i].RowCount
columnCount = ranges[i].ColumnCount
if rowCount > 1 and columnCount > 1:
for j in range(startRow, startRow + rowCount):
table.ApplyHorizontalMerge(j - 1, startColumn - 1, startColumn - 1 + columnCount - 1)
table.ApplyVerticalMerge(startColumn - 1, startRow - 1, startRow - 1 + rowCount - 1)
if rowCount > 1 and columnCount == 1:
table.ApplyVerticalMerge(startColumn - 1, startRow - 1, startRow - 1 + rowCount - 1)
if columnCount > 1 and rowCount == 1:
table.ApplyHorizontalMerge(startRow - 1, startColumn - 1, startColumn - 1 + columnCount - 1)
def CopyStyle(wTextRange, xCell, wCell):
"""Copy cell styling from Excel to Word."""
# Copy font style
wTextRange.CharacterFormat.TextColor = Color.FromRgb(xCell.Style.Font.Color.R, xCell.Style.Font.Color.G, xCell.Style.Font.Color.B)
wTextRange.CharacterFormat.FontSize = float(xCell.Style.Font.Size)
wTextRange.CharacterFormat.FontName = xCell.Style.Font.FontName
wTextRange.CharacterFormat.Bold = xCell.Style.Font.IsBold
wTextRange.CharacterFormat.Italic = xCell.Style.Font.IsItalic
# Copy background color
if xCell.Style.FillPattern is not ExcelPatternType.none:
wCell.CellFormat.Shading.BackgroundPatternColor=Color.FromRgb(xCell.Style.Color.R, xCell.Style.Color.G, xCell.Style.Color.B)
# Copy horizontal alignment
if xCell.HorizontalAlignment == HorizontalAlignType.Left:
wTextRange.OwnerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Left
elif xCell.HorizontalAlignment == HorizontalAlignType.Center:
wTextRange.OwnerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Center
elif xCell.HorizontalAlignment == HorizontalAlignType.Right:
wTextRange.OwnerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Right
# Copy vertical alignment
if xCell.VerticalAlignment == VerticalAlignType.Bottom:
wCell.CellFormat.VerticalAlignment = VerticalAlignment.Bottom
elif xCell.VerticalAlignment == VerticalAlignType.Center:
wCell.CellFormat.VerticalAlignment = VerticalAlignment.Middle
elif xCell.VerticalAlignment == VerticalAlignType.Top:
wCell.CellFormat.VerticalAlignment = VerticalAlignment.Top
# Load an Excel file
workbook = Workbook()
workbook.LoadFromFile("Contact list.xlsx")
# Get the first worksheet
sheet = workbook.Worksheets[0]
# Create a Word document
doc = Document()
section = doc.AddSection()
section.PageSetup.Orientation = PageOrientation.Landscape
# Add a table
table = section.AddTable(True)
table.ResetCells(sheet.LastRow, sheet.LastColumn)
# Merge cells
MergeCells(sheet, table)
# Export data and styles from Excel to Word table
for r in range(1, sheet.LastRow + 1):
table.Rows[r - 1].Height = float(sheet.Rows[r - 1].RowHeight)
for c in range(1, sheet.LastColumn + 1):
xCell = sheet.Range[r, c]
wCell = table.Rows[r - 1].Cells[c - 1]
# Add text from Excel to Word table cell
textRange = wCell.AddParagraph().AppendText(xCell.NumberText)
# Copy font and cell style
CopyStyle(textRange, xCell, wCell)
# Save the document to a Word file
doc.SaveToFile("ConvertExcelDataToWordTable.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: Find and Highlight Data in Excel Worksheets
Efficiently emphasizing critical data within Excel workbooks is essential for swift analysis. This process not only draws immediate attention to the most relevant information but also aids in identifying trends, anomalies, and key metrics. By using Python to handle Excel workbooks, users can automate the search and highlight functions, enhancing productivity and ensuring precision. This article explores how to leverage Python for finding and highlighting data in Excel worksheets using Spire.XLS for Python library.
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 commands.
pip install Spire.XLS
If you are unsure how to install, please refer to: How to Install Spire.XLS for Python on Windows
Find and Highlight Data in Excel Worksheets
Using Spire.XLS for Python, we can find all cells containing a specific string and return them as a list by using the Worksheet.FindAllString(stringValue: str, formula: bool, formulaValue: bool) method. After that, we can iterate through the found cells and apply a highlight color by setting it via the CellRange.Style.Color property.
The detailed steps for finding and highlighting data in an Excel worksheet are as follows:
- Create an instance of Workbook class and load an Excel workbook using Workbook.LoadFromFile() method.
- Get a worksheet using Workbook.Worksheets.get_Item() method.
- Find all the cells containing the string to be highlighted using Worksheet.FindAllString() method.
- Iterate through the results to highlight the cells by setting a fill color through CellRange.Style.Color property.
- Save the workbook using Workbook.SaveToFile() method.
- Python
from spire.xls import *
# Create an instance of Workbook
workbook = Workbook()
# Load an Excel file
workbook.LoadFromFile("Sample.xlsx")
# Get the first worksheet
sheet = workbook.Worksheets.get_Item(0)
# Find the data to be highlighted
cellRanges = sheet.FindAllString("Urgent", False, True)
# Iterate through the found ranges
for cellRange in cellRanges:
# Highlight the data
cellRange.Style.Color = Color.get_LightYellow()
# Save the workbook
workbook.SaveToFile("output/FindHighlightDataExcel.xlsx")
workbook.Dispose()

Find and Highlight Data in a Specific Cell Range
In addition to searching for data across the entire worksheet, we can use the CellRange.FindAllString(stringValue: str, formula: bool, formulaValue: bool) method to find and highlight data within a specified cell range. The detailed steps are as follows:
- Workbook.LoadFromFile() method.
- Get a worksheet using Workbook.Worksheets.get_Item() method.
- Get a cell range through Worksheet.Range[] property.
- Find all the cells containing the string to be highlighted using CellRange.FindAllString() method.
- Iterate through the results to highlight the cells by setting a fill color through CellRange.Style.Color property.
- Save the workbook using Workbook.SaveToFile() method.
- Python
from spire.xls import *
# Create an instance of Workbook
workbook = Workbook()
# Load an Excel file
workbook.LoadFromFile("Sample.xlsx")
# Get the first worksheet
sheet = workbook.Worksheets.get_Item(0)
# Get the cell range
findRange = sheet.Range["C1:C11"]
# Find the data to be highlighted
cellRanges = findRange.FindAllString("Urgent", False, True)
# Iterate the found ranges
for cellRange in cellRanges:
# Highlight the data
cellRange.Style.Color = Color.get_LightYellow()
# Save the workbook
workbook.SaveToFile("output/FindHighlightRange.xlsx")
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.
Python: Extract or Update Textboxes in a Word Document
Textboxes in a Word document serve as versatile containers for text, enabling users to enhance layout and design. They allow for the separation of content from the main body, making documents more visually appealing and organized. Extracting or updating textboxes can be essential for improving document efficiency, ensuring information is current, and facilitating data analysis.
In this article, you will learn how to extract or update textboxes in a Word document using Python and 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
Extract Text from a Textbox in Word
Using Spire.Doc for Python, you can access a specific text box in a document by utilizing the Document.TextBoxes[index] property. After retrieving the text box, you can iterate through its child objects to identify whether each one is a paragraph or a table. If the object is a paragraph, you can retrieve its text using the Paragraph.Text property. In cases where the object is a table, you will need to loop through each cell to extract text from every individual cell within that table.
The steps to extract text from a text box in a Word document are as follows:
- Create a Document object.
- load a Word file by using Document.LoadFromFile() method.
- Access a specific text box using Document.TextBoxes[index] property.
- Iterate through the child objects within the text box.
- Determine if a child object is a paragraph. If it is, retrieve the text from the paragraph using Paragraph.Text property.
- Check if a child object is a table. If so, iterate through the cells in the table to extract text from each cell.
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
document = Document()
# Load a Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")
# Get a specific textbox
textBox = document.TextBoxes.get_Item(0)
with open('ExtractedText.txt','w') as sw:
# Iterate through the child objects in the textbox
for i in range(textBox.ChildObjects.Count):
# Get a specific child object
object = textBox.ChildObjects.get_Item(i)
# Determine if the child object is paragraph
if object.DocumentObjectType == DocumentObjectType.Paragraph:
# Write paragraph text to txt file
sw.write((object if isinstance(object, Paragraph) else None).Text + "\n")
# Determine if the child object is table
if object.DocumentObjectType == DocumentObjectType.Table:
table = object if isinstance(object, Table) else None
for i in range(table.Rows.Count):
row = table.Rows[i]
for j in range(row.Cells.Count):
cell = row.Cells[j]
for k in range(cell.Paragraphs.Count):
paragraph = cell.Paragraphs.get_Item(k)
# Write paragrah text of a specific cell to txt file
sw.write(paragraph.Text + "\n")
# Dispose resources
document.Dispose()

Update Text in a Textbox in Word
To update a textbox in a Word document, start by clearing its existing content with the TextBox.ChildObjects.Clear() method. This action removes all child objects, including any paragraphs or tables currently contained within the textbox. After clearing the content, you can add a new paragraph to the text box. Once the paragraph is created, set its text to the desired value.
The steps to update a textbox in a Word document are as follows:
- Create a Document object.
- Load a Word file using Document.LoadFromFile() method.
- Get a specific textbox using Document.TextBoxes[index] property
- Remove existing content of the textbox using TextBox.ChildObjects.Clear() method.
- Add a paragraph to the textbox using TextBox.Body.AddParagraph() method.
- Add text to the paragraph using Paragraph.AppendText() method.
- Save the document to a different Word file.
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
document = Document()
# Load a Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.docx")
# Get a specific textbox
textBox = document.TextBoxes.get_Item(0)
# Remove child objects of the textbox
textBox.ChildObjects.Clear()
# Add a new paragraph to the textbox
paragraph = textBox.Body.AddParagraph()
# Set line spacing
paragraph.Format.LineSpacing = 15.0
# Add text to the paragraph
textRange = paragraph.AppendText("The text in this textbox has been updated.")
# Set font size
textRange.CharacterFormat.FontSize = 15.0
# Save the document to a different Word file
document.SaveToFile("UpdateTextbox.docx", FileFormat.Docx2019);
# Dispose resources
document.Dispose()

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Python: Crop Pages in PDF
When dealing with PDF files, you might sometimes need to crop pages in the PDF to remove unnecessary margins, borders, or unwanted content. By doing so, you can make the document conform to specific design requirements or page sizes, ensuring a more aesthetically pleasing or functionally optimized output. This article will introduce how to crop pages in PDF in Python using Spire.PDF for Python.
Install Spire.PDF for Python
This scenario requires Spire.PDF for Python. It 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
Crop a PDF Page in Python
Spire.PDF for Python allows you specify a rectangular area, and then use the PdfPageBase.CropBox property to crop page to the specified area. The following are the detailed steps.
- Create a PdfDocument instance.
- Load a PDF file using PdfDocument.LoadFromFile() method.
- Get a specified page using PdfDocument.Pages[] property.
- Crop the page to the specified area using PdfPageBase.CropBox property.
- Save the result file using PdfDocument.SaveToFile() method.
- Python
from spire.pdf.common import *
from spire.pdf import *
# Create a PdfDocument object
pdf = PdfDocument()
# Load a PDF file from disk
pdf.LoadFromFile("Sample1.pdf")
# Get the first page
page = pdf.Pages.get_Item(0)
# Crop the page by the specified area
page.CropBox = RectangleF(0.0, 300.0, 600.0, 260.0)
# Save the result file
pdf.SaveToFile("CropPDF.pdf")
pdf.Close()

Crop a PDF Page and Export as an Image in Python
To accomplish this task, you can use the PdfDocument.SaveAsImage(pageIndex: int) method to convert a cropped PDF page to an image stream. The following are the detailed steps.
- Create a PdfDocument instance.
- Load a PDF file using PdfDocument.LoadFromFile() method.
- Get a specified page using PdfDocument.Pages[] property.
- Crop the page to the specified area using PdfPageBase.CropBox property.
- Convert the cropped page to an image stream using PdfDocument.SaveAsImage() method.
- Save the image as a PNG, JPG or BMP file using Stream.Save() method.
- Python
from spire.pdf.common import *
from spire.pdf import *
# Create a PdfDocument object
pdf = PdfDocument()
# Load a PDF file from disk
pdf.LoadFromFile("Sample1.pdf")
# Get the first page
page = pdf.Pages.get_Item(0)
# Crop the page by the specified area
page.CropBox = RectangleF(0.0, 300.0, 600.0, 260.0)
# Convert the page to an image
with pdf.SaveAsImage(0) as imageS:
# Save the image as a PNG file
imageS.Save("CropPDFSaveAsImage.png")
pdf.Close()

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: Set the Transparency of PDF Images
Setting the transparency of images in PDF documents is crucial for achieving professional-grade output, which allows for layering images without hard edges and creating a seamless integration with the background or underlying content. This not only enhances the visual appeal but also creates a polished and cohesive look, especially in graphics-intensive documents. This article will demonstrate how to effectively set the transparency of PDF images using Spire.PDF for Python 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
Add Images with Specified Transparency to PDF
Developers can utilize the PdfPageBase.Canvas.DrawImage() method in Spire.PDF for Python to draw an image at a specified location on a PDF page. Before drawing, developers can set the transparency of the canvas using PdfPageBase.Canvas.SetTransparency() method, which in turn sets the transparency level of the image being drawn. Below are the detailed steps:
- Create an object of PdfDocument class and load a PDF document using PdfDocument.LoadFromFile() method.
- Get a page in the document using PdfDocument.Pages.get_Item() method.
- Load an image using PdfImage.FromFile() method.
- Set the transparency of the canvas using PdfPageBase.Canvas.SetTransparency() method.
- Draw the image on the page using PdfPageBase.Canvas.DrawImage() method.
- Save the document using PdfDocument.SaveToFile() method.
- Python
from spire.pdf import *
# Create a PdfDocument instance
pdf = PdfDocument()
# Load a PDF file
pdf.LoadFromFile("Sample.pdf")
# Get the first page
page = pdf.Pages.get_Item(0)
# Load an image
image = PdfImage.FromFile("Screen.jpg")
# Set the transparency of the canvas
page.Canvas.SetTransparency(0.2)
# Draw the image at the specified location
page.Canvas.DrawImage(image, PointF(80.0, 80.0))
# Save the document
pdf.SaveToFile("output/AddTranslucentPicture.pdf")
pdf.Close()

Adjust the Transparency of Existing Images in PDF
To adjust the transparency of an existing image on a PDF page, developers can retrieve the image along with its bounds, delete the image, and finally redraw the image in the same location with the specified transparency. This process allows for the adjustment of the image's opacity while maintaining its original placement. The detailed steps are as follows:
- Create an object of PdfDocument class and load a PDF document using PdfDocument.LoadFromFile() method.
- Get a page in the document using PdfDocument.Pages.get_Item() method.
- Get an image on the page as a stream through PdfPageBase.ImagesInfo[].Image property and get the bounds of the image through PdfPageBase.ImagesInfo[].Bounds property.
- Remove the image from the page using PdfPageBase.DeleteImage() method.
- Create a PdfImage instance with the stream using PdfImage.FromStream() method.
- Set the transparency of the canvas using PdfPageBase.Canvas.SetTransparency() method.
- Redraw the image in the same location with the specified transparency using PdfPageBase.Canvas.DrawImage() method.
- Save the document using PdfDocument.SaveToFile() method.
- Python
from spire.pdf import *
# Create a PdfDocument instance
pdf = PdfDocument()
# Load a PDF file
pdf.LoadFromFile("Sample1.pdf")
# Get the first page
page = pdf.Pages.get_Item(0)
# Get the first image on the page as a stream and the bounds of the image
imageHelper = PdfImageHelper()
imageInformation = imageHelper.GetImagesInfo(page)
bounds = imageInformation[0].Bounds
imageStream =imageInformation[0].Image
# Delete the original image
imageHelper.DeleteImage(imageInformation[0])
# Create a PdfImage instance using the image stream
image = PdfImage.FromStream(imageStream)
# Create a PdfImage instance using the image stream
image = PdfImage.FromStream(imageStream)
# Set the transparency of the canvas
page.Canvas.SetTransparency(0.3)
# Draw the new image at the same location using the canvas
page.Canvas.DrawImage(image, bounds)
# Save the document
pdf.SaveToFile("output/SetExistingImageTransparency.pdf")
pdf.Close()

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.
C#: Set Page Setup Options in Excel
When printing Excel spreadsheets, particularly those containing complex datasets or detailed reports, configuring the page setup properly is crucial. Excel’s page setup options enable you to adjust key factors such as page margins, orientation, paper size, and scaling, ensuring your documents are tailored to fit various printing needs. By customizing these settings, you can control how your content is displayed on the page, making sure it appears polished and professional. In this article, we will demonstrate how to set page setup options in Excel in C# using Spire.XLS for .NET.
- Set Page Margins in Excel in C#
- Set Page Orientation in Excel in C#
- Set Paper Size in Excel in C#
- Set Print Area in Excel in C#
- Set Scaling Factor in Excel in C#
- Set Fit-to-Pages Options in Excel in C#
- Set Headers and Footers in Excel in C#
Install Spire.XLS for .NET
To begin with, you need to add the DLL files included in the Spire.XLS for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.XLS
Set Page Margins in Excel in C#
The PageSetup class in Spire.XLS for .NET is used to configure page setup options for Excel worksheets. You can access the PageSetup object of a worksheet through the Worksheet.PageSetup property. Then, use properties like PageSetup.TopMargin, PageSetup.BottomMargin, PageSetup.LeftMargin, PageSetup.RightMargin, PageSetup.HeaderMarginInch, and PageSetup.FooterMarginInch to set the corresponding margins for the worksheet. The detailed steps are as follows.
- Create an object of the Workbook class.
- Load an Excel file using Workbook.LoadFromFile() method.
- Get a specific worksheet using Workbook.Worksheets[index] property.
- Access the PageSetup object of the worksheet using Worksheet.PageSetup property.
- Set the top, bottom, left, right, header, and footer margins using PageSetup.TopMargin, PageSetup.BottomMargin, PageSetup.LeftMargin, PageSetup.RightMargin, PageSetup.HeaderMarginInch, and PageSetup.FooterMarginInch properties.
- Save the modified workbook to a new file using Workbook.SaveToFile() method.
- C#
using Spire.Xls;
namespace SetPageMargins
{
internal class Program
{
static void Main(string[] args)
{
// Create a Workbook object
Workbook workbook = new Workbook();
// Load an Excel file
workbook.LoadFromFile("Sample.xlsx");
// Get the first worksheet
Worksheet sheet = workbook.Worksheets[0];
// Get the PageSetup object of the worksheet
PageSetup pageSetup = sheet.PageSetup;
// Set top, bottom, left, and right page margins for the worksheet
// The measure of the unit is Inch (1 inch = 2.54 cm)
pageSetup.TopMargin = 1;
pageSetup.BottomMargin = 1;
pageSetup.LeftMargin = 1;
pageSetup.RightMargin = 1;
pageSetup.HeaderMarginInch = 1;
pageSetup.FooterMarginInch = 1;
// Save the modified workbook to a new file
workbook.SaveToFile("SetPageMargins.xlsx", ExcelVersion.Version2016);
workbook.Dispose();
}
}
}

Set Page Orientation in Excel in C#
The PageSetup.Orientation property lets you determine how the page should be oriented when printed. You can choose between two options: portrait mode or landscape mode. The detailed steps are as follows.
- Create an object of the Workbook class.
- Load an Excel file using Workbook.LoadFromFile() method.
- Get a specific worksheet using Workbook.Worksheets[index] property.
- Access the PageSetup object of the worksheet using Worksheet.PageSetup property.
- Set the page orientation using PageSetup.Orientation property.
- Save the modified workbook to a new file using Workbook.SaveToFile() method.
- C#
using Spire.Xls;
namespace SetPageOrientation
{
internal class Program
{
static void Main(string[] args)
{
// Create a Workbook object
Workbook workbook = new Workbook();
// Load an Excel file
workbook.LoadFromFile("Sample.xlsx");
// Get the first worksheet
Worksheet sheet = workbook.Worksheets[0];
// Get the PageSetup object of the worksheet
PageSetup pageSetup = sheet.PageSetup;
// Set the page orientation for printing the worksheet to landscape mode
pageSetup.Orientation = PageOrientationType.Landscape;
// Save the modified workbook to a new file
workbook.SaveToFile("SetPageOrientation.xlsx", ExcelVersion.Version2016);
workbook.Dispose();
}
}
}

Set Paper Size in Excel in C#
The PageSetup.PaperSize property enables you to select from a variety of paper sizes for printing your worksheet. These options include A3, A4, A5, B4, B5, letter, legal, tabloid, and more. The detailed steps are as follows.
- Create an object of the Workbook class.
- Load an Excel file using Workbook.LoadFromFile() method.
- Get a specific worksheet using Workbook.Worksheets[index] property.
- Access the PageSetup object of the worksheet using Worksheet.PageSetup property.
- Set the paper size using PageSetup.PaperSize property.
- Save the modified workbook to a new file using Workbook.SaveToFile() method.
- C#
using Spire.Xls;
namespace SetPaperSize
{
internal class Program
{
static void Main(string[] args)
{
// Create a Workbook object
Workbook workbook = new Workbook();
// Load an Excel file
workbook.LoadFromFile("Sample.xlsx");
// Get the first worksheet
Worksheet sheet = workbook.Worksheets[0];
// Get the PageSetup object of the worksheet
PageSetup pageSetup = sheet.PageSetup;
// Set the paper size to A4
pageSetup.PaperSize = PaperSizeType.PaperA4;
// Save the modified workbook to a new file
workbook.SaveToFile("SetPaperSize.xlsx", ExcelVersion.Version2016);
workbook.Dispose();
}
}
}

Set Print Area in Excel in C#
You can specify the exact area that you want to print using the PageSetup.PringArea property. The detailed steps are as follows.
- Create an object of the Workbook class.
- Load an Excel file using Workbook.LoadFromFile() method.
- Get a specific worksheet using Workbook.Worksheets[index] property.
- Access the PageSetup object of the worksheet using Worksheet.PageSetup property.
- Set the print area using PageSetup.PringArea property.
- Save the modified workbook to a new file using Workbook.SaveToFile() method.
- C#
using Spire.Xls;
namespace SetPrintArea
{
internal class Program
{
static void Main(string[] args)
{
// Create a Workbook object
Workbook workbook = new Workbook();
// Load an Excel file
workbook.LoadFromFile("Sample.xlsx");
// Get the first worksheet
Worksheet sheet = workbook.Worksheets[0];
// Get the PageSetup object of the worksheet
PageSetup pageSetup = sheet.PageSetup;
// Set the print area of the worksheet to "A1:E5"
pageSetup.PrintArea = "A1:E5";
// Save the modified workbook to a new file
workbook.SaveToFile("SetPrintArea.xlsx", ExcelVersion.Version2016);
workbook.Dispose();
}
}
}

Set Scaling Factor in Excel in C#
If you want to scale the content of your worksheet to a specific percentage of its original size, use the PageSetup.Zoom property. The detailed steps are as follows.
- Create an object of the Workbook class.
- Load an Excel file using Workbook.LoadFromFile() method.
- Get a specific worksheet using Workbook.Worksheets[index] property.
- Access the PageSetup object of the worksheet using Worksheet.PageSetup property.
- Set the scaling factor using PageSetup.Zoom property.
- Save the modified workbook to a new file using Workbook.SaveToFile() method.
- C#
using Spire.Xls;
namespace SetScalingFactor
{
internal class Program
{
static void Main(string[] args)
{
// Create a Workbook object
Workbook workbook = new Workbook();
// Load an Excel file
workbook.LoadFromFile("Sample.xlsx");
// Get the first worksheet
Worksheet sheet = workbook.Worksheets[0];
// Get the PageSetup object of the worksheet
PageSetup pageSetup = sheet.PageSetup;
// Set the scaling factor of the worksheet to 90%
pageSetup.Zoom = 90;
// Save the modified workbook to a new file
workbook.SaveToFile("SetScalingFactor.xlsx", ExcelVersion.Version2016);
workbook.Dispose();
}
}
}

Set Fit-to-Pages Options in Excel in C#
Spire.XLS also enables you to fit your worksheet content to a specific number of pages by using the PageSetup.FitToPagesTall and PageSetup.FitToPagesWide properties. The detailed steps are as follows.
- Create an object of the Workbook class.
- Load an Excel file using Workbook.LoadFromFile() method.
- Get a specific worksheet using Workbook.Worksheets[index] property.
- Access the PageSetup object of the worksheet using Worksheet.PageSetup property.
- Fit the content of the worksheet to one page using PageSetup.FitToPagesTall and PageSetup.FitToPagesWide properties.
- Save the modified workbook to a new file using Workbook.SaveToFile() method.
- C#
using Spire.Xls;
namespace SetFitToPages
{
internal class Program
{
static void Main(string[] args)
{
// Create a Workbook object
Workbook workbook = new Workbook();
// Load an Excel file
workbook.LoadFromFile("Sample.xlsx");
// Get the first worksheet
Worksheet sheet = workbook.Worksheets[0];
// Get the PageSetup object of the worksheet
PageSetup pageSetup = sheet.PageSetup;
// Fit the content of the worksheet within one page vertically (i.e., all rows will fit on a single page)
pageSetup.FitToPagesTall = 1;
// Fit the content of the worksheet within one page horizontally (i.e., all columns will fit on a single page)
pageSetup.FitToPagesWide = 1;
// Save the modified workbook to a new file
workbook.SaveToFile("FitToPages.xlsx", ExcelVersion.Version2016);
workbook.Dispose();
}
}
}

Set Headers and Footers in Excel in C#
For setting headers and footers in Excel, please check this article: C#/VB.NET: Add Headers and Footers to 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.