Python: Insert or Extract Images in Word Tables

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

Install Spire.Doc for Python

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

pip install Spire.Doc

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

Insert Images into a Word Table in Python

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

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

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

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

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

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

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

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

Python: Insert or Extract Images in Word Tables

Extract Images from a Word Table in Python

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

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

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

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

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

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

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

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

doc.Close()

Python: Insert or Extract Images in Word Tables

Apply for a Temporary License

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