Replace Placeholders in a Word Document Using Python

Alexander Stock
3 min readDec 13, 2023

--

Automating the process of filling in specific information or variables within a template is a common task when working with Word documents. Replacing placeholders offers an efficient and accurate way to customize documents, eliminating the need for manual editing of each instance. By leveraging this approach, users can streamline their workflow and ensure consistency in document creation. In this article, I am going to introduce how to find and replace placeholders in a Word template by using the Spire.Doc for Python library.

Install Dependency

This solution requires Spire.Doc for Python to be installed as a dependency, which is a Python library for reading, creating and manipulating Word documents in a Python program. You can install Spire.Doc for Python by executing the following pip command.

pip install Spire.Doc

P.S. Spire.Doc for Python is a commercial library that requires a paid license. There is a red watermark in the generated document if no license is applied.

Create a Template Using MS Word

Here is a screenshot of the MS Word-generated template. The placeholders “#name#”, “#address#” are intended to be replaced with new strings, while the placeholder “#photo#” will be substituted with an image. Don’t forget to format the placeholders so that the new content inherits these formatting settings (font size, style, alignment, etc.).

Replace Placeholders in Word Using Python

The steps to replace placeholders in a Word template using Spire.Doc for Python are as follows.

  • Create a Document object.
  • Load the Word template using Document.LoadFromFile() method.
  • Get the placeholders and new strings stored in a dictionary.
  • Replace the placeholders with new strings using Document.Replace(matchString, newValue, caseSensitive, wholeWord) method.
  • Replace the placeholder with an image using the custom method ReplaceTextWithImage(document, stringToReplace, imagePath).
  • Save the document to a Word file using Document.SaveToFile() method.
from spire.doc import *
from spire.doc.common import *

# Replace string in a Word document with an image
def ReplaceTextWithImage(document, stringToReplace, imagePath):

# Find a specific text in the document
selections = document.FindAllString(stringToReplace, True, True)
# Load an image
pic = DocPicture(document)
pic.LoadImage(imagePath)
# Get a certain text
selection = selections[0]
# Get the found text as a single text range
range = selection.GetAsOneRange()
# Get the index of the text range in its owner paragraph
index = range.OwnerParagraph.ChildObjects.IndexOf(range)
# Insert an image at the index
range.OwnerParagraph.ChildObjects.Insert(index, pic)
# Remove the text range
range.OwnerParagraph.ChildObjects.Remove(range)

# Create a Document object
document = Document()

# Load the template
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Template.docx")

# Store the placeholders and new strings in a dictionary
dictionary = {"#name#":"Jackson Wong",\
"#address#": "123 Michigan Street, Bloomfield, MI94141",\
"#telephone#":"537286",\
"#email#": "jackson@hotmail.com",\
"#nationality#":"United States",\
"#birthday#": "July 12th, 1992",\
"#gender#": "Male"}

# Loop through the items in the dictionary
for key,value in dictionary.items():

# Replace a placeholder (key) with a new string (value)
document.Replace(key, value, False, True)

# Replace a placeholder with an image
ReplaceTextWithImage(document, "#photo#", "C:\\Users\\Administrator\\Desktop\\portrait.jpg")

# Save the resulting document
document.SaveToFile("output/ReplacePlaceholder.docx", FileFormat.Docx2016)
document.Close()

Output

--

--

Alexander Stock

I'm Alexander Stock, a software development consultant and blogger with 10+ years' experience. Specializing in office document tools and knowledge introduction.