Python: Extract Images from PowerPoint Presentations
Extracting images from a PowerPoint presentation is necessary when you need to reuse them elsewhere. By doing so, you gain the flexibility to use these images outside the confines of the original presentation, thus maximizing their value in different projects. This article will demonstrate how to extract images from a PowerPoint document 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
Extract Images from a PowerPoint Document in Python
To extract images from an entire PowerPoint presentation, you need to use the Presentation.Images property to get the collection of all the images in the presentation, then iterate through the elements in the collection and call IImageData.Image.Save() method to save each element to an image file. The following are the detailed steps:
- Create a Presentation instance.
- Load a PowerPoint document using Presentation.LoadFromFile() method.
- Get the collection of all the images in the document using Presentation.Images property.
- Iterate through the elements in the collection, and save each element as an image file using the IImageData.Image.Save() method.
- Python
from spire.presentation.common import *
from spire.presentation import *
# Create a Presentation instance
ppt = Presentation()
# Load a PowerPoint document
ppt.LoadFromFile("sample.pptx")
# Iterate through all images in the document
for i, image in enumerate(ppt.Images):
# Extract the images
ImageName = "ExtractImage/Images_"+str(i)+".png"
image.Image.Save(ImageName)
ppt.Dispose()

Extract Images from a Presentation Slide in Python
To extract images from a specific slide, you need to iterate through all shapes on the slide and find the shapes that are of SlidePicture or PictureShape type, then use the SlidePicture.PictureFill.Picture.EmbedImage.Image.Save() or PictureShape.EmbedImage.Image.Save() method to save the images to image files. The following are the detailed steps:
- Create a Presentation instance.
- Load a PowerPoint document using Presentation.LoadFromFile() method.
- Get a specified slide using Presentation.Slides[int] property.
- Iterate through all shapes on the slide.
- Determine whether the shapes are of SlidePicture or PictureShape type. If so, save the images to image files using SlidePicture.PictureFill.Picture.EmbedImage.Image.Save() or PictureShape.EmbedImage.Image.Save() method.
- Python
from spire.presentation.common import *
from spire.presentation import *
# Create a Presentation instance
ppt = Presentation()
# Load a PowerPoint document
ppt.LoadFromFile("sample.pptx")
# Get a specified slide
slide = ppt.Slides[2]
i = 0
#Traverse all shapes in the slide
for s in slide.Shapes:
# Determine if the shape is of SlidePicture type
if isinstance(s, SlidePicture):
# If yes, then extract the image
ps = s if isinstance(s, SlidePicture) else None
ps.PictureFill.Picture.EmbedImage.Image.Save("Output/SlidePic_"+str(i)+".png")
i += 1
# Determine if the shape is of PictureShape type
if isinstance(s, PictureShape):
# If yes, then extract the image
ps = s if isinstance(s, PictureShape) else None
ps.EmbedImage.Image.Save("Output/SlidePic_"+str(i)+".png")
i += 1
ppt.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: Apply Superscript and Subscript in Excel
Superscript and subscript are formatting styles used in typography and writing to position characters or numbers above or below the normal line of text. Superscript is a smaller-sized text or symbol that is raised above the baseline. It is commonly used for mathematical exponents, footnotes, and ordinal indicators. Subscript, on the other hand, is a smaller-sized text or symbol that is positioned below the baseline. It is often used for chemical formulas, mathematical expressions and some linguistic notations. These formatting styles can help users distinguish specific elements within text and convey information more effectively. In this article, we will show you how to apply superscript and subscript in Excel by 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
Apply Superscript and Subscript in Excel
To apply the superscript or subscript style to specific characters in excel, you need to create a custom font first and set the superscript or subscript property of it. And then assign the font to the specific characters within the cell using CellRange.RichText.SetFont() method provided by Spire.XLS for Python. The detailed steps are as follows:
- Create an object of Workbook class.
- Get the first worksheet of it using Workbook.Worksheets[int index] property.
- Get the specific cells using Worksheet.Range[string name] property and add desired text to them.
- Get a cell by using Worksheet.Range[string name] property and add rich text to it by CellRange.RichText.Text property.
- Create a custom font using Workbook.CreateFont() method.
- Enable the subscript property of the font by setting ExcelFont.IsSubscript property to true.
- Assign the font to specific characters of the added rich text in the cell by calling CellRange.RichText.SetFont() method.
- Likewise, get another cell using Worksheet.Range[string name] property and add rich text to it by CellRange.RichText.Text property.
- Create a custom font using Workbook.CreateFont() method.
- Enable the superscript property of the font by setting ExcelFont.IsSuperscript property to true.
- Assign the font to specific characters of the added rich text in the cell by calling CellRange.RichText.SetFont() method.
- Automatically adjust column widths to fit text length using Worksheet.AllocatedRange.AutoFitColumns() method.
- Save the result file using Workbook.SaveToFile() method.
- Python
from spire.xls import * from spire.xls.common import * outputFile = "ApplySubscriptAndSuperscript.xlsx" # Create an object of Workbook class workbook = Workbook() # Get the first worksheet sheet = workbook.Worksheets[0] # Add text to the specific cells sheet.Range["B2"].Text = "This is an example of Subscript:" sheet.Range["D2"].Text = "This is an example of Superscript:" # Add rich text to a specific cell range = sheet.Range["B3"] range.RichText.Text = "an = Sn - Sn-1" # Create a custom font font = workbook.CreateFont() # Enable the subscript property of the font by setting the IsSubscript property to "true" font.IsSubscript = True # Set the font color font.Color = Color.get_Green() # Assign the font to specific characters of the added rich text range.RichText.SetFont(6, 6, font) range.RichText.SetFont(11, 13, font) # Add rich text to another cell range = sheet.Range["D3"] range.RichText.Text = "a2 + b2 = c2" # Create a custom font font = workbook.CreateFont() # Enable the superscript property of the font by setting the IsSuperscript property to "true" font.IsSuperscript = True # Assign the font to specific characters of the added rich text range.RichText.SetFont(1, 1, font) range.RichText.SetFont(6, 6, font) range.RichText.SetFont(11, 11, font) # Autofit the column widths sheet.AllocatedRange.AutoFitColumns() # Save the result file workbook.SaveToFile(outputFile, ExcelVersion.Version2013) 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: Set a Background Color or Image for PDF
Applying a background color or image to a PDF can be an effective way to enhance its visual appeal, create a professional look, or reinforce branding elements. By adding a background, you can customize the overall appearance of your PDF document and make it more engaging for readers. Whether you want to use a solid color or incorporate a captivating image, this feature allows you to personalize your PDFs and make them stand out. In this article, you will learn how to set a background color or image for a PDF document in Python using Spire.PDF for Python.
Install Spire.PDF for Python
This scenario requires Spire.PDF for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.
pip install Spire.PDF
If you are unsure how to install, please refer to this tutorial: How to Install Spire.PDF for Python on Windows
Set a Background Color for PDF in Python
Spire.PDF for Python offers the PdfPageBase.BackgroundColor property to get or set the background color of a certain page. To add a solid color to the background of each page in the document, follow the steps below.
- Create a PdfDocument object.
- Load a PDF file using PdfDocument.LoadFromFile() method.
- Traverse through the pages in the document, and get a specific page through PdfDocument.Pages[index] property.
- Apply a solid color to the background through PdfPageBase.BackgroundColor property.
- Save the document to a different PDF file 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("C:\\Users\\Administrator\\Desktop\\input.pdf")
# Loop through the pages in the document
for i in range(doc.Pages.Count):
# Get a particular page
page = doc.Pages.get_Item(i)
# Set background color
page.BackgroundColor = Color.get_LightYellow()
# Save the document to a different file
doc.SaveToFile("output/SetBackgroundColor.pdf")

Set a Background Image for PDF in Python
Likewise, an image can be applied to the background of a specific page via PdfPageBase.BackgroundImage property. The steps to set an image background for the entire document are as follows.
- Create a PdfDocument object.
- Load a PDF file using PdfDocument.LoadFromFile() method.
- Traverse through the pages in the document, and get a specific page through PdfDocument.Pages[index] property.
- Apply an image to the background through PdfPageBase.BackgroundImage property.
- Save the document to a different PDF file 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("C:\\Users\\Administrator\\Desktop\\input.pdf")
# Loop through the pages in the document
for i in range(doc.Pages.Count):
# Get a particular page
page = doc.Pages.get_Item(i)
# Set background image
page.BackgroundImage = Stream("C:\\Users\\Administrator\\Desktop\\img.jpg")
# Save the document to a different file
doc.SaveToFile("output/SetBackgroundImage.pdf")

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Python: Rotate PDF Pages
If you receive or download a PDF file and find that some of the pages are displayed in the wrong orientation (e.g., sideways or upside down), rotating the PDF file allows you to correct the page orientation for easier reading and viewing. This article will demonstrate how to programmatically rotate PDF pages 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
Rotate a Specific Page in PDF in Python
Rotation is based on 90-degree increments. You can rotate a PDF page by 0/90/180/270 degrees. The following are the steps to rotate a PDF page:
- Create a PdfDocument object.
- Load a PDF document using PdfDocument.LoadFromFile() method.
- Get a specified page using PdfDocument.Pages[pageIndex] property.
- Get the original rotation angle of the page using PdfPageBase.Rotation.value property.
- Increase the original rotation angle by desired degrees.
- Apply the new rotation angle to the page using PdfPageBase.Rotation property
- Save the result document using PdfDocument.SaveToFile() method.
- Python
from spire.pdf.common import *
from spire.pdf import *
# Create a PdfDocument object
pdf = PdfDocument()
# Load a PDF document
pdf.LoadFromFile("Sample.pdf")
# Get the first page
page = doc.Pages.get_Item(0)
# Get the original rotation angle of the page
rotation = int(page.Rotation.value)
# Rotate the page 180 degrees clockwise based on the original rotation angle
rotation += int(PdfPageRotateAngle.RotateAngle180.value)
page.Rotation = PdfPageRotateAngle(rotation)
# Save the result document
pdf.SaveToFile("RotatePDFPage.pdf")
pdf.Close()

Rotate All Pages in PDF in Python
Spire.PDF for Python also allows you to loop through each page in a PDF file and then rotate them all. The following are the detailed steps.
- Create a PdfDocument object.
- Load a PDF document using PdfDocument.LoadFromFile() method.
- Loop through each page in the document.
- Get the original rotation angle of the page using PdfPageBase.Rotation.value property.
- Increase the original rotation angle by desired degrees.
- Apply the new rotation angle to the page using PdfPageBase.Rotation property.
- Save the result document using PdfDocument.SaveToFile() method.
- Python
from spire.pdf.common import *
from spire.pdf import *
# Create a PdfDocument object
pdf = PdfDocument()
# Load a PDF document
pdf.LoadFromFile("Input.pdf")
# Loop through each page in the document
for i in range(pdf.Pages.Count):
page = pdf.Pages.get_Item(i)
# Get the original rotation angle of the page
rotation = int(page.Rotation.value)
# Rotate the page 180 degrees clockwise based on the original rotation angle
rotation += int(PdfPageRotateAngle.RotateAngle180.value)
page.Rotation = PdfPageRotateAngle(rotation)
# Save the result document
pdf.SaveToFile("RotatePDF.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.
Convert PDF to Images in Python (PNG, JPG, BMP, SVG, TIFF)

Converting PDF files to images in Python is a common need for developers and professionals working with digital documents. Whether you want to generate thumbnails, create previews, extract specific content areas, or prepare files for printing, transforming a PDF into image formats gives you flexibility and compatibility across platforms.
This comprehensive guide demonstrates how to convert PDF files into popular image formats—such as PNG, JPG, BMP, SVG, and TIFF—in Python, using practical, easy-to-follow code examples.
Table of Contents
- Why Convert PDF to Image
- Python PDF-to-Image Converter Library
- Simple PDF to PNG, JPG, and BMP Conversion
- Advanced Conversion Options
- Generate Multi-Page TIFF from PDF
- Export PDF as SVG
- Conclusion
- FAQs
Why Convert PDF to Image?
Converting PDF to image formats offers several benefits:
- Cross-platform compatibility: Images are easier to embed in web pages, mobile apps, or presentations.
- Preview and thumbnail generation: Quickly create page snapshots without rendering the full PDF.
- Selective content extraction: Save specific areas of a PDF as images for focused analysis or reuse.
- Simplified sharing: Images can be easily emailed, uploaded, or displayed without special PDF readers.
Python PDF-to-Image Converter Library
Spire.PDF for Python is a powerful and easy-to-use library designed for handling PDF files. It enables developers to convert PDF pages into multiple image formats like PNG, JPG, BMP, SVG, and TIFF with excellent quality and performance.

Installation
You can easily install the library using pip. Simply open your terminal and run the following command:
pip install Spire.PDF
Simple PDF to PNG, JPG, and BMP Conversion
The SaveAsImage method of the PdfDocument class allows you to render each page of a PDF into an image format of your choice.
The code example below demonstrates how to load a PDF file, iterate through its pages, and save each one as a PNG image. You can easily adjust the file format to JPG or BMP by changing the file extension.
from spire.pdf import *
# Load the PDF file
pdf = PdfDocument()
pdf.LoadFromFile("template.pdf")
# Loop through pages and save as images
for i in range(pdf.Pages.Count):
# Convert each page to image
with pdf.SaveAsImage(i) as image:
# Save in different formats as needed
image.Save(f"Output/ToImage_{i}.png")
# image.Save(f"Output/ToImage_{i}.jpg")
# image.Save(f"Output/ToImage_{i}.bmp")
# Close the PDF document
pdf.Close()

Advanced Conversion Options
Enable Transparent Image Background
Transparent backgrounds help integrate images seamlessly into designs, avoiding unwanted borders or background colors.
To enable a transparent background during PDF-to-image conversion in Python, use the SetPdfToImageOptions() method with an alpha value of 0. This setting ensures that the background of the output image is fully transparent.
The following example demonstrates how to export each PDF page as a transparent PNG image.
from spire.pdf import *
# Load PDF document from file
pdf = PdfDocument()
pdf.LoadFromFile("template.pdf")
# Set the transparent value of the image's background to 0
pdf.ConvertOptions.SetPdfToImageOptions(0)
# Loop through all pages and save each as an image
for i in range(pdf.Pages.Count):
# Convert each page to an image
with pdf.SaveAsImage(i) as image:
# Save the image to the output directory
image.Save(f"Output/ToImage_{i}_transparent.png")
# Close the PDF document
pdf.Close()
Note: Transparency is supported in PNG but not in JPG or BMP formats.
Crop Specific PDF Areas to Image
In some cases, you may only need to export a specific area of a PDF page—such as a chart, table, or block of text. This can be done by adjusting the page’s CropBox before rendering.
The CropBox property defines the visible region of the page used for display and printing. By setting it to a specific RectangleF(x, y, width, height) value, you can isolate and export only the desired portion of the content.
The example below demonstrates how to crop a rectangular area on the first page of a PDF and save that section as a PNG image.
from spire.pdf import *
# Load the PDF document from file
pdf = PdfDocument()
pdf.LoadFromFile("Sample.pdf")
# Access the first page of the PDF
page = doc.Pages.get_Item(0)
# Define the crop area of the page using a rectangle (x, y, width, height)
page.CropBox = RectangleF(0.0, 300.0, 600.0, 260.0)
# Convert the cropped page to an image
with pdf.SaveAsImage(0) as image:
# Save the image to a PNG file
image.Save("Output/CropPDFSaveAsImage.png")
# Close the PDF document
pdf.Close()
Note: You need to adjust the coordinates based on the location of your target content. Coordinates start from the top-left corner of the page.

Generate Multi-Page TIFF from PDF
The TIFF format supports multi-page documents, making it a popular choice for archival and printing purposes. Although Spire.PDF for Python doesn't natively create multi-page TIFFs, you can render individual pages as images and then use the Pillow library to merge them into one .tiff file.
Before proceeding, ensure Pillow is installed by running:
pip install Pillow
The following example illustrates how to:
- Load a PDF
- Convert each page to an image
- Combine all images into a single multi-page TIFF
from spire.pdf import *
from PIL import Image
from io import BytesIO
# Load the PDF document from file
pdf = PdfDocument()
pdf.LoadFromFile("Input.pdf")
# Create an empty list to store PIL Images
images = []
# Iterate through all pages in the document
for i in range(pdf.Pages.Count):
# Convert a specific page to an image stream
with pdf.SaveAsImage(i) as imageData:
# Open the image stream as a PIL image
img = Image.open(BytesIO(imageData.ToArray()))
# Append the PIL image to list
images.append(img)
# Save the PIL Images as a multi-page TIFF file
images[0].save("Output/ToTIFF.tiff", save_all=True, append_images=images[1:])
# Dispose resources
pdf.Dispose()

It’s also possible to convert TIFF files back to PDF. For detailed instructions on it, please refer to the tutorial: Python: Convert PDF to TIFF and TIFF to PDF.
Export PDF as SVG
SVG (Scalable Vector Graphics) is an ideal format for content that requires scaling without quality loss, such as charts, vector illustrations, and technical diagrams.
By using the SaveToFile() method with the FileFormat.SVG option, you can export PDF pages as SVG files. This conversion preserves the vector characteristics of the content, making it well-suited for web embedding, responsive design, and further editing in vector graphic tools.
The following example demonstrates how to export an entire PDF document to SVG format.
from spire.pdf import *
# Load the PDF document from file
pdf = PdfDocument()
pdf.LoadFromFile("Example.pdf")
# Save each page of the file to a separate SVG file
pdf.SaveToFile("PdfToSVG/ToSVG.svg", FileFormat.SVG)
# Close the PdfDocument object
pdf.Close()
Note: Each page in the PDF will be saved as a separate SVG file named ToSVG_i.svg, where i is the page number (1-based).
To export specific pages or customize the SVG output size, please refer to our detailed guide: Python: Convert PDF to SVG.
Conclusion
Converting PDF to images in formats like PNG, JPG, BMP, SVG, and TIFF provides flexibility for sharing, displaying, and processing digital documents. With Spire.PDF for Python, you can:
- Export high-quality images from PDFs in various formats
- Crop specific regions for focused content extraction
- Generate multi-page TIFF files for archival purposes
- Create scalable SVG vector graphics for diagrams and charts
By automating PDF to image conversion in Python, you can seamlessly integrate image export into your applications and workflows.
FAQs
Q1: Can I convert a range of pages from a PDF to images?
A1: Yes. You can convert specific pages by specifying their indices in a loop. For example, to export pages 1 to 3:
# Convert only pages 1-3
for i in range(0, 3): # 0-based index
with pdf.SaveAsImage(i) as img:
img.Save(f"page_{i}.png")
Q2: Can I batch convert multiple PDF files to images?
A2: Yes, batch conversion is supported. You can iterate through a list of PDF file paths and convert each one within a loop.
pdf_files = ["a.pdf", "b.pdf", "c.pdf"]
for file in pdf_files:
pdf = PdfDocument()
pdf.LoadFromFile(file)
for i in range(pdf.Pages.Count):
with pdf.SaveAsImage(i) as img:
img.Save(f"{file}_page_{i}.png")
Q3: Is it possible to convert password-protected PDFs to images?
A3: Yes, you can convert secured PDFs to images as long as you provide the correct password when loading the PDF document.
pdf = PdfDocument()
pdf.LoadFromFile("protected.pdf", "password")
Q4: Is it possible to extract embedded images from a PDF instead of rendering pages?
A4: Yes. Aside from rendering entire pages, the library also supports extracting images directly from the PDF.
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.
Python: Add or Delete Table Rows and Columns in Word
Adding or removing rows and columns in a Word table allows you to adjust the table's structure to accommodate your data effectively. By adding rows and columns, you can effortlessly expand the table as your data grows, ensuring that all relevant information is captured and displayed in a comprehensive manner. On the other hand, removing unnecessary rows and columns allows you to streamline the table, eliminating any redundant or extraneous data that may clutter the document. In this article, we will demonstrate how to add or delete table rows and columns in Word in Python using Spire.Doc for Python.
- Add or Insert a Row into a Word Table in Python
- Add or Insert a Column into a Word Table in Python
- Delete a Row from a Word Table in Python
- Delete a Column from a Word Table in 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 or Insert a Row into a Word Table in Python
You can add a row to the end of a Word table or insert a row at a specific location of a Word table using the Table.AddRow() or Table.InsertRow() method. The following are the detailed steps:
- Create a Document object.
- Load a Word document using Document.LoadFromFile() method.
- Get the first section of the document using Document.Sections[] property.
- Get the first table of the section using Section.Tables[] property.
- Insert a row at a specific location of the table using Table.Rows.Insert() method.
- Add data to the newly inserted row.
- Add a row to the end of the table using Table.AddRow() method.
- Add data to the newly added row.
- Save the resulting document using Document.SaveToFile() method.
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
document = Document()
# Load a Word document
document.LoadFromFile("Table1.docx")
# Get the first section of the document
section = document.Sections.get_Item(0)
# Get the first table of the first section
table = section.Tables.get_Item(0) if isinstance(section.Tables.get_Item(0), Table) else None
# Insert a row into the table as the third row
table.Rows.Insert(2, table.AddRow())
# Get the inserted row
insertedRow = table.Rows[2]
# Add data to the row
for i in range(insertedRow.Cells.Count):
cell = insertedRow.Cells[i]
paragraph = cell.AddParagraph()
paragraph.AppendText("Inserted Row")
paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle
# Add a row at the end of the table
addedRow = table.AddRow()
# Add data to the row
for i in range(addedRow.Cells.Count):
cell = addedRow.Cells[i]
paragraph = cell.AddParagraph()
paragraph.AppendText("End Row")
paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle
# Save the resulting document
document.SaveToFile("AddRows.docx", FileFormat.Docx2016)
document.Close()

Add or Insert a Column into a Word Table in Python
Spire.Doc for Python doesn't offer a direct method to add or insert a column into a Word table. But you can achieve this by adding or inserting cells at a specific location of each table row using TableRow.Cells.Add() or TableRow.Cells.Insert() method. The detailed steps are as follows:
- Create a Document object.
- Load a Word document using Document.LoadFromFile() method.
- Get the first section of the document using Document.Sections[] property.
- Get the first table of the section using Section.Tables[] property.
- Loop through each row of the table.
- Create a TableCell object, then insert it at a specific location of each row using TableRow.Cells.Insert() method and set cell width.
- Add data to the cell and set text alignment.
- Add a cell to the end of each row using TableRow.AddCell() method and set cell width.
- Add data to the cell and set text alignment.
- Save the resulting document using Document.SaveToFile() method.
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
document = Document()
# Load a Word document
document.LoadFromFile("Table1.docx")
# Get the first section of the document
section = document.Sections.get_Item(0)
# Get the first table of the first section
table = section.Tables.get_Item(0) if isinstance(section.Tables.get_Item(0), Table) else None
# Loop through the rows of the table
for i in range(table.Rows.Count):
row = table.Rows.get_Item(i)
# Create a TableCell object
cell = TableCell(document)
# Insert the cell as the third cell of the row and set cell width
row.Cells.Insert(2, cell)
cell.Width = row.Cells[0].Width
# Add data to the cell
paragraph = cell.AddParagraph()
paragraph.AppendText("Inserted Column")
# Set text alignment
paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle
# Add a cell to the end of the row and set cell width
cell = row.AddCell()
cell.Width = row.Cells[1].Width
# Add data to the cell
paragraph = cell.AddParagraph()
paragraph.AppendText("End Column")
# Set text alignment
paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle
# Save the resulting document
document.SaveToFile("AddColumns.docx", FileFormat.Docx2016)
document.Close()

Delete a Row from a Word Table in Python
To delete a specific row from a Word table, you can use the Table.Rows.RemoveAt() method. The detailed steps are as follows:
- Create a Document object.
- Load a Word document using Document.LoadFromFile() method.
- Get the first section of the document using Document.Sections[] property.
- Get the first table of the section using Section.Tables[] property.
- Remove a specific row from the table using Table.Rows.RemoveAt() method.
- Save the resulting document using Document.SaveToFile() method.
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
document = Document()
# Load a Word document
document.LoadFromFile("AddRows.docx")
# Get the first section of the document
section = document.Sections.get_Item(0)
# Get the first table of the first section
table = section.Tables.get_Item(0) if isinstance(section.Tables.get_Item(0), Table) else None
# Remove the third row
table.Rows.RemoveAt(2)
# Remove the last row
table.Rows.RemoveAt(table.Rows.Count - 1)
# Save the resulting document
document.SaveToFile("RemoveRows.docx", FileFormat.Docx2016)
document.Close()

Delete a Column from a Word Table in Python
To delete a specific column from a Word table, you need to remove the corresponding cell from each table row using the TableRow.Cells.RemoveAt() method. The detailed steps are as follows:
- Create a Document object.
- Load a Word document using Document.LoadFromFile() method.
- Get the first section of the document using Document.Sections[] property.
- Get the first table of the section using Section.Tables[] property.
- Loop through each row of the table.
- Remove a specific cell from each row using TableRow.Cells.RemoveAt() method.
- Save the resulting document using Document.SaveToFile() method.
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
document = Document()
# Load a Word document
document.LoadFromFile("AddColumns.docx")
# Get the first section of the document
section = document.Sections.get_Item(0)
# Get the first table of the first section
table = section.Tables.get_Item(0) if isinstance(section.Tables.get_Item(0), Table) else None
# Loop through the rows of the table
for i in range(table.Rows.Count):
row = table.Rows.get_Item(i)
# Remove the third cell from the row
row.Cells.RemoveAt(2)
# Remove the last cell from the row
row.Cells.RemoveAt(row.Cells.Count - 1)
# Save the resulting document
document.SaveToFile("RemoveColumns.docx", FileFormat.Docx2016)
document.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: Hide or Unhide Excel Worksheets
The Excel workbook is a powerful spreadsheet that enables the creation, manipulation, and analysis of data in a variety of ways. One of the useful features that workbooks offer is the ability to hide or unhide worksheets in a workbook. Hiding worksheets can help protect sensitive or confidential information, reduce clutter, or organize data more efficiently. And when users need to re-display the hidden worksheets, they can also unhide them with simple operations. This article is going to explain how to hide or unhide worksheets in Excel workbooks through Python programs using Sprie.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
Hide Excel Worksheets in Python
The Worksheet.Visibility property in Spire.XLS for Python can be used to set the visibility of a worksheet. By assigning WorksheetVisibility.Hidden or WorksheetVisibility.StrongHidden to this property, users can change the visibility of a worksheet to hidden or very hidden (completely not shown in Excel and can only be unhidden through code).
The detailed steps for hiding worksheets are as follows:
- Create an object of Workbook class.
- Load a workbook using Workbook.LoadFromFile() method.
- Change the status of the first worksheet to hidden by assigning WorksheetVisibility.Hidden to the Workbook.Worksheets[].Visibility property.
- Change the status of the second worksheet to very hidden by assigning WorksheetVisibility.StrongHidden to the Workbook.Worksheets[].Visibility property.
- Save the workbook using Workbook.SaveToFile() method.
- Python
from spire.xls import *
# Create an object of Workbook
workbook = Workbook()
# Load an Excel workbook
workbook.LoadFromFile("Sample.xlsx")
# Hide the first worksheet
workbook.Worksheets[0].Visibility = WorksheetVisibility.Hidden
# Change the second worksheet to very hidden
workbook.Worksheets[1].Visibility = WorksheetVisibility.StrongHidden
# Save the workbook
workbook.SaveToFile("output/HideWorksheets.xlsx")

Unhide Excel Worksheets in Python
Unhiding a worksheet can be done by assigning WorksheetVisibility.Visible to the Workbook.Worksheets[].Visibility property. The detailed steps are as follows:
- Create an object of Workbook class.
- Load a workbook using Workbook.LoadFromFile() method.
- Unhide the very hidden worksheet by assigning WorksheetVisibility.Visible to the Workbook.Worksheets[].Visibility property.
- Save the workbook using Workbook.SaveToFile() method.
- Python
from spire.xls import *
# Create an object of Workbook
workbook = Workbook()
# Load an Excel workbook
workbook.LoadFromFile("output/HideWorksheets.xlsx")
# Unhide the second worksheet
workbook.Worksheets[0].Visibility = WorksheetVisibility.Visible
# Save the workbook
workbook.SaveToFile("output/UnhideWorksheet.xlsx")

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Python: Add Comments in Excel
Comment in Excel is a function that allows users to add extra details or remarks as explanatory notes. Comments can be in the form of text or images. It enables users to provide additional information to explain or supplement the data in specified cells. After adding a comment, users can view the content of the comment by hovering the mouse over the cell with the comment. This feature enhances the readability and comprehensibility of the document, helping readers better understand and handle the data in Excel. In this article, we will show you how to add comments in Excel by 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 Comment with Text in Excel
Spire.XLS for Python allows users to add comment with text in Excel by calling CellRange.AddComment() method. The following are detailed steps.
- Create an object of Workbook class.
- Load an Excel file using Workbook.LoadFromFile() method.
- Get the first worksheet of this file using Workbook.Worksheets[] property.
- Get the specified cell by using Worksheet.Range[] property.
- Set the author and content of the comment and add them to the obtained cell using CellRange.AddComment() method.
- Set the font of the comment.
- Save the result file using Workbook.SaveToFile() method.
- Python
from spire.xls import * from spire.xls.common import * inputFile = "sample.xlsx" outputFile = "CommentWithAuthor.xlsx" #Create an object of Workbook class workbook = Workbook() #Load the sample file from disk workbook.LoadFromFile(inputFile) #Get the first worksheet sheet = workbook.Worksheets[0] #Get the specified cell range = sheet.Range["B4"] #Set the author and content of the comment author = "Jhon" text = "Emergency task." #Add comment to the obtained cell comment = range.AddComment() comment.Width = 200 comment.Visible = True comment.Text = author + ":\n" + text #Set the font of the comment font = workbook.CreateFont() font.FontName = "Tahoma" font.KnownColor = ExcelColors.Black font.IsBold = True comment.RichText.SetFont(0, len(author), font) #Save the result file workbook.SaveToFile(outputFile, ExcelVersion.Version2013) workbook.Dispose()

Add Comment with Picture in Excel
Additionally, Spire.XLS for Python also enable users to add comment with picture to the specified cell in Excel by using CellRange.AddComment() and ExcelCommentObject.Fill.CustomPicture() methods. The following are detailed steps.
- Create an object of Workbook class.
- Get the first worksheet using Workbook.Worksheets[] property.
- Get the specified cell by using Worksheet.Range[] property and set text for it.
- Add comment to the obtained cell by using CellRange.AddComment() method.
- Load an image and fill the comment with it by calling ExcelCommentObject.Fill.CustomPicture() method.
- Set the height and width of the comment.
- Save the result file using Workbook.SaveToFile() method.
- Python
from spire.xls import * from spire.xls.common import * inputFile = "logo.png" outputFile = "CommentWithPicture.xlsx" #Create an object of Workbook class workbook = Workbook() #Get the first worksheet sheet = workbook.Worksheets[0] #Get the specified cell and set text for it range = sheet.Range["C6"] range.Text = "E-iceblue" #Add comment to the obtained cell comment = range["C6"].AddComment() #Load an image file and fill the comment with it image = Image.FromFile(inputFile) comment.Fill.CustomPicture(image, "logo.png") #Set the height and width of the comment comment.Height = image.Height comment.Width = image.Width comment.Visible = True #Save the result file workbook.SaveToFile(outputFile, ExcelVersion.Version2010) 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 Text and Images from Word Documents
By extracting text from Word documents, you can effortlessly obtain the written information contained within them. This allows for easier manipulation, analysis, and organization of textual content, enabling tasks such as text mining, sentiment analysis, and natural language processing. Extracting images, on the other hand, provides access to visual elements embedded within Word documents, which can be crucial for tasks like image recognition, content extraction, or creating image databases. In this article, you will learn how to extract text and images from a Word document in Python using Spire.Doc for Python.
- Extract Text from a Specific Paragraph in Python
- Extract Text from an Entire Word Document in Python
- Extract Images from an Entire Word Document in 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 Specific Paragraph in Python
To get a certain paragraph from a section, use Section.Paragraphs[index] property. Then, you can get the text of the paragraph through Paragraph.Text property. The detailed steps are as follows.
- Create a Document object.
- Load a Word file using Document.LoadFromFile() method.
- Get a specific section through Document.Sections[index] property.
- Get a specific paragraph through Section.Paragraphs[index] property.
- Get text from the paragraph through Paragraph.Text property.
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
doc = Document()
# Load a Word document
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")
# Get a specific section
section = doc.Sections.get_Item(0)
# Get a specific paragraph
paragraph = section.Paragraphs.get_Item(2)
# Get text from the paragraph
str = paragraph.Text
# Print result
print(str)

Extract Text from an Entire Word Document in Python
If you want to get text from a whole document, you can simply use Document.GetText() method. Below are the steps.
- Create a Document object.
- Load a Word file using Document.LoadFromFile() method.
- Get text from the document using Document.GetText() method.
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
doc = Document()
# Load a Word file
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")
# Get text from the entire document
str = doc.GetText()
# Print result
print(str)

Extract Images from an Entire Word Document in Python
Spire.Doc for Python does not provide a straightforward method to get images from a Word document. You need to iterate through the child objects in the document, and determine if a certain a child object is a DocPicture. If yes, you get the image data using DocPicture.ImageBytes property and then save it as a popular image format file. The main steps are as follows.
- Create a Document object.
- Load a Word file using Document.LoadFromFile() method.
- Loop through the child objects in the document.
- Determine if a specific child object is a DocPicture. If yes, get the image data through DocPicture.ImageBytes property.
- Write the image data as a PNG file.
- Python
import queue
from spire.doc import *
from spire.doc.common import *
# Create a Document object
doc = Document()
# Load a Word file
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")
# Create a Queue object
nodes = queue.Queue()
nodes.put(doc)
# Create a list
images = []
while nodes.qsize() > 0:
node = nodes.get()
# Loop through the child objects in the document
for i in range(node.ChildObjects.Count):
child = node.ChildObjects.get_Item(i)
# Determine if a child object is a picture
if child.DocumentObjectType == DocumentObjectType.Picture:
picture = child if isinstance(child, DocPicture) else None
dataBytes = picture.ImageBytes
# Add the image data to the list
images.append(dataBytes)
elif isinstance(child, ICompositeObject):
nodes.put(child if isinstance(child, ICompositeObject) else None)
# Loop through the images in the list
for i, item in enumerate(images):
fileName = "Image-{}.png".format(i)
with open("ExtractedImages/"+fileName,'wb') as imageFile:
# Write the image to a specified path
imageFile.write(item)
doc.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: Create, Read, or Update a Word Document
Creating, reading, and updating Word documents is a common need for many developers working with the Python programming language. Whether it's generating reports, manipulating existing documents, or automating document creation processes, having the ability to work with Word documents programmatically can greatly enhance productivity and efficiency. In this article, you will learn how to create, read, or update Word documents in Python using Spire.Doc for Python.
- Create a Word Document from Scratch in Python
- Read Text of a Word Document in Python
- Update a Word Document in 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
Create a Word Document from Scratch in Python
Spire.Doc for Python offers the Document class to represent a Word document model. A document must contain at least one section (represented by the Section class) and each section is a container for various elements such as paragraphs, tables, charts, and images. This example shows you how to create a simple Word document containing several paragraphs using Spire.Doc for Python.
- Create a Document object.
- Add a section using Document.AddSection() method.
- Set the page margins through Section.PageSetUp.Margins property.
- Add several paragraphs to the section using Section.AddParagraph() method.
- Add text to the paragraphs using Paragraph.AppendText() method.
- Create a ParagraphStyle object, and apply it to a specific paragraph using Paragraph.ApplyStyle() method.
- Save the document to a Word file using Document.SaveToFile() method.
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
doc = Document()
# Add a section
section = doc.AddSection()
# Set the page margins
section.PageSetup.Margins.All = 40
# Add a title
titleParagraph = section.AddParagraph()
titleParagraph.AppendText("Introduction of Spire.Doc for Python")
# Add two paragraphs
bodyParagraph_1 = section.AddParagraph()
bodyParagraph_1.AppendText("Spire.Doc for Python is a professional Python library designed for developers to " +
"create, read, write, convert, compare and print Word documents in any Python application " +
"with fast and high-quality performance.")
bodyParagraph_2 = section.AddParagraph()
bodyParagraph_2.AppendText("As an independent Word Python API, Spire.Doc for Python doesn't need Microsoft Word to " +
"be installed on neither the development nor target systems. However, it can incorporate Microsoft Word " +
"document creation capabilities into any developers' Python applications.")
# Apply heading1 to the title
titleParagraph.ApplyStyle(BuiltinStyle.Heading1)
# Create a style for the paragraphs
style2 = ParagraphStyle(doc)
style2.Name = "paraStyle"
style2.CharacterFormat.FontName = "Arial"
style2.CharacterFormat.FontSize = 13
doc.Styles.Add(style2)
bodyParagraph_1.ApplyStyle("paraStyle")
bodyParagraph_2.ApplyStyle("paraStyle")
# Set the horizontal alignment of the paragraphs
titleParagraph.Format.HorizontalAlignment = HorizontalAlignment.Center
bodyParagraph_1.Format.HorizontalAlignment = HorizontalAlignment.Left
bodyParagraph_2.Format.HorizontalAlignment = HorizontalAlignment.Left
# Set the after spacing
titleParagraph.Format.AfterSpacing = 10
bodyParagraph_1.Format.AfterSpacing = 10
# Save to file
doc.SaveToFile("output/WordDocument.docx", FileFormat.Docx2019)

Read Text of a Word Document in Python
To get the text of an entire Word document, you could simply use Document.GetText() method. The following are the detailed steps.
- Create a Document object.
- Load a Word document using Document.LoadFromFile() method.
- Get text from the entire document using Document.GetText() method.
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
doc = Document()
# Load a Word file
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\WordDocument.docx")
# Get text from the entire document
text = doc.GetText()
# Print text
print(text)

Update a Word Document in Python
To access a specific paragraph, you can use the Section.Paragraphs[index] property. If you want to modify the text of the paragraph, you can reassign text to the paragraph through the Paragraph.Text property. The following are the detailed steps.
- Create a Document object.
- Load a Word document using Document.LoadFromFile() method.
- Get a specific section through Document.Sections[index] property.
- Get a specific paragraph through Section.Paragraphs[index] property.
- Change the text of the paragraph through Paragraph.Text property.
- Save the document to another Word file using Document.SaveToFile() method.
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
doc = Document()
# Load a Word file
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\WordDocument.docx")
# Get a specific section
section = doc.Sections.get_Item(0)
# Get a specific paragraph
paragraph = section.Paragraphs.get_Item(1)
# Change the text of the paragraph
paragraph.Text = "The title has been changed"
# Save to file
doc.SaveToFile("output/Updated.docx", FileFormat.Docx2019)

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.