Python: Replace Images in Word

2023-11-10 01:09:35 Written by  support iceblue
Rate this item
(0 votes)

Images play a crucial role in effectively communicating complex ideas or concepts. When there are low-quality or outdated images in a Word document, it is necessary to replace the images to enhance the overall visual appeal and professionalism of your document. In this article, you will learn how to replace images in a Word document in Python using Spire.Doc for Python.

Install Spire.Doc for Python

This scenario requires Spire.Doc for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip 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

Replace Image with New Image in Word in Python

Spire.Doc for Python supports not only inserting images in Word, but also replacing existing images. The following are the detailed steps to get a specific image in Word and then replace it with a new image.

  • Create a Document object.
  • Load a Word document using Document.LoadFromFile() method.
  • Create a list to store the images.
  • Iterate through all sections in the document.
  • Iterate through all paragraphs in each section.
  • Iterate through all child objects in each paragraph.
  • Find the images and add them to the list.
  • Get a specific image from the list and replace it with another image using DocPicture.LoadImage() method.
  • Save the result document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
doc = Document()

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

# Create a list to store the images
pictures = []

# Iterate through all sections in the document
for i in range(doc.Sections.Count):
    sec = doc.Sections.get_Item(i)

    # Iterate through all paragraphs in each section
    for j in range(sec.Paragraphs.Count):
        para = sec.Paragraphs.get_Item(j)

        # Iterate through all child objects in each paragraph
        for k in range(para.ChildObjects.Count):
            docObj = para.ChildObjects.get_Item(k)

            # Find the images and add them to the list
            if docObj.DocumentObjectType == DocumentObjectType.Picture:
                pictures.append(docObj)

# Replace the first picture in the list with a new image
picture = pictures[0] if isinstance(pictures[0], DocPicture) else None
picture.LoadImage("data.jpg")

# Save the result document
doc.SaveToFile("ReplaceImage.docx", FileFormat.Docx)
doc.Close()

Python: Replace Images in Word

Replace Image with Text in Word in Python

Spire.Doc for Python doesn't provide a direct method to replace image with text, but you can achieve this task by inserting text at the image location and then removing the image from the document.

The following are the steps to replace all images in a Word document with text:

  • Create a Document object.
  • Load a Word document using Document.LoadFromFile() method.
  • Iterate through all sections in the document.
  • Iterate through all paragraphs in each section.
  • Create a list to store the images.
  • Iterate through all child objects in each paragraph.
  • Find the images and add them to the list.
  • Iterate through the images in the list.
  • Get the index of the image in the paragraph using Paragraph.ChildObjects.Indexof() method.
  • Initialize an instance of TextRange class and set text for the text range through TextRange.Text property.
  • Insert the text range at the image location using Paragraph.ChildObjects.Insert() method.
  • Remove the image from the paragraph using Paragraph.ChildObjects.Remove() method.
  • Save the result document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
doc = Document()

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

j = 1
# Iterate through all sections in the document
for k in range(doc.Sections.Count):
    sec = doc.Sections.get_Item(k)

    # Iterate through all sections in the document
    for m in range(sec.Paragraphs.Count):
        para = sec.Paragraphs.get_Item(m)

        # Create a list to store the images
        pictures = []

        # Find the images and add them to the list
        for x in range(para.ChildObjects.Count):
            docObj = para.ChildObjects.get_Item(x)
            if docObj.DocumentObjectType == DocumentObjectType.Picture:
                pictures.append(docObj)

        # Iterate through all images in the list and replace them with text "Here is image {image index}"
        for pic in pictures:
            index = para.ChildObjects.IndexOf(pic)
            textRange = TextRange(doc)
            textRange.Text = "Here is image {0}".format(j)
            para.ChildObjects.Insert(index, textRange)
            para.ChildObjects.Remove(pic)
            j += 1

# Save the result document
doc.SaveToFile("ReplaceWithText.docx", FileFormat.Docx)
doc.Close()

Python: Replace Images in Word

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.

Additional Info

  • tutorial_title:
Last modified on Thursday, 25 April 2024 02:10