Create Word Documents from Templates with Python

2024-01-05 07:29:41

Templates provide a ready-made structure and layout, saving you time and effort in creating documents from scratch. Instead of designing the document layout, formatting styles, and section organization, you can simply choose a template that meets your requirements and start adding your content. This is particularly useful when you need to create multiple documents with a consistent look and feel. In this blog, we will explore how to create Word documents from templates using Python.

We will discuss three different approaches for generating Word documents from templates:

Python Library to Create Word Documents from Templates

To begin with, we need to install the necessary Python module that supports Word document generation from templates. In this blog post, we will be using the Spire.Doc for Python library.

Spire.Doc for Python offers a comprehensive set of features for creating, reading, editing, and converting Word files within Python applications. It provides seamless support for various Word formats including Doc, Docx, Docm, Dot, Dotx, Dotm, and more. Additionally, it enables high-quality conversion of Word documents to different formats, such as Word to PDF, Word to RTF, Word to HTML, Word to Text, and Word to Image.

To install Spire.Doc for Python, you can run the following pip command:

pip install Spire.Doc

For detailed installation instructions, please refer to this documentation: How to Install Spire.Doc for Python in VS Code.

Create Word Documents from Templates by Replacing Placeholder Text in Python

"Placeholder text" refers to temporary text that can be easily replaced with the desired content. To create a Word document from a template by replacing placeholder text, you need to prepare a template that includes predefined placeholder text. This template can be manually created using the Microsoft Word application or programmatically generated with Spire.Doc for Python.

Here are the steps to create a Word document from a template by replacing placeholder text using Spire.Doc for Python:

  • Create a Document instance and then load a Word template using Document.LoadFromFile() method.
  • Define a dictionary that maps placeholder text to their corresponding replacement text for performing replacements in the document.
  • Loop through the dictionary.
  • Replace the placeholder text in the document with the corresponding replacement text using Document.Replace() method.
  • Save the resulting document using Document.SaveToFile() method.

Here is a code example that creates a Word document from a template by replacing placeholder text using Spire.Doc for Python:

  • Python
from spire.doc import *
from spire.doc.common import *

# Specify the input and output file paths
inputFile = "Placeholder_Template.docx"
outputFile = "CreateDocumentByReplacingPlaceholderText.docx"

# Create a Document object
document = Document()
# Load a Word template with placeholder text
document.LoadFromFile(inputFile)

# Create a dictionary to store the placeholder text and its corresponding replacement text
# Each key represents a placeholder, while the corresponding value represents the replacement text
text_replacements = {
    "{name}": "John Smith",
    "{email}": "johnsmith@example.com",
    "{telephone}": "(123) 456-7890",
    "{address}": "123 Main Street, A City, B State",
    "{education}": "B.S. in Computer Science \nXYZ University \n2010 - 2014",
    "{experience}": "Software Engineer \nABC Company \n2015 - Present",
    "{skills}": "Programming (Python, Java, C++) \nProject Management \nProblem Solving",
    "{projects}": "Developed a mobile app for XYZ Company, resulting in a 20% increase in user engagement. \nLed a team of 5 developers to successfully deliver a complex software project on time and within budget.",
    "{certifications}": "Project Management Professional (PMP) \nMicrosoft Certified: Azure Developer Associate",
    "{languages}": "English (Fluent) \nSpanish (Intermediate)",
    "{interests}": "Traveling, Photography, Reading"
}

# Loop through the dictionary
for placeholder_text, replacement_text in text_replacements.items():
    # Replace the placeholder text in the document with the replacement text
    document.Replace(placeholder_text, replacement_text, False, False)

# Save the resulting document
document.SaveToFile(outputFile, FileFormat.Docx2016)
document.Close()

Create Word Documents from Templates with Python

Tips: This example explained how to replace placeholder text in a Word template with new text. It's worth noting that Spire.Doc for Python supports replacing text in various scenarios, including replacing text with images, replacing text with tables, replacing text using regex, and more. You can find more details in this documentation: Python: Find and Replace Text in Word.

Create Word Documents from Templates by Replacing Bookmarks in Python

Bookmarks in a Word document serve as reference points that allow you to precisely insert or replace content at specific locations within the document. To create a Word document from a template by replacing bookmarks, you need to prepare a template that contains predefined bookmarks. This template can be manually created using the Microsoft Word application or programmatically generated with Spire.Doc for Python.

Here are the steps to create a Word document from a template by replacing bookmarks using Spire.Doc for Python:

  • Create a Document instance and load a Word document using Document.LoadFromFile() method.
  • Define a dictionary that maps bookmark names to their corresponding replacement text for performing replacements in the document.
  • Loop through the dictionary.
  • Create a BookmarksNavigator instance and navigate to the specific bookmark by its name using BookmarkNavigator.MoveToBookmark() method.
  • Replace the content of the bookmark with the corresponding replacement text using BookmarkNavigator.ReplaceBookmarkContent() method.
  • Save the resulting document using Document.SaveToFile() method.

Here is a code example that creates a Word document from a template by replacing bookmarks using Spire.Doc for Python:

  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()
# Load a Word template with bookmarks
document.LoadFromFile("Template_Bookmark.docx")

# Create a dictionary to store the bookmark names and their corresponding replacement text
# Each key represents a bookmark name, while the corresponding value represents the replacement text
bookmark_replacements = {
    "introduction": "In today's digital age, effective communication is crucial.",
    "methodology": "Our research approach focuses on gathering qualitative data.",
    "results": "The analysis reveals significant findings supporting our hypothesis.",
    "conclusion": "Based on our findings, we recommend further investigation in this field."
}

# Loop through the dictionary
for bookmark_name, replacement_text in bookmark_replacements.items():
    # Replace the content of the bookmarks in the document with the corresponding replacement text
    bookmarkNavigator = BookmarksNavigator(document)
    bookmarkNavigator.MoveToBookmark(bookmark_name)
    bookmarkNavigator.ReplaceBookmarkContent(replacement_text, True)
    # Remove the bookmarks from the document
    document.Bookmarks.Remove(bookmarkNavigator.CurrentBookmark)

# Save the resulting document
document.SaveToFile("CreateDocumentByReplacingBookmark.docx", FileFormat.Docx2016)
document.Close()

Create Word Documents from Templates with Python

Create Word Documents from Templates by Performing Mail Merge in Python

Mail merge is a powerful feature in Microsoft Word that allows you to create customized documents from a template by merging it with a data source. To create a Word document from a template by performing mail merge, you need to prepare a template that includes predefined merge fields. This template can be manually created using the Microsoft Word application, or programmatically generated with Spire.Doc for Python using the following code:

  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()
# Add a section
section = document.AddSection()
# Set page margins
section.PageSetup.Margins.All = 72.0

# Add a paragraph  
paragraph = section.AddParagraph()
# Add text to the paragraph
paragraph.AppendText("Customer Name: ")

# Add a paragraph  
paragraph = section.AddParagraph()
# Add a merge field to the paragraph  
paragraph.AppendField("Recipient Name", FieldType.FieldMergeField)  
  
# Save the resulting document 
document.SaveToFile("Template.docx", FileFormat.Docx2013)
document.Close()

Here are the steps to create a Word document from a template by performing mail merge using Spire.Doc for Python:

  • Create a Document instance and then load a Word template using Document.LoadFromFile() method.
  • Define a list of merge field names.
  • Define a list of merge field values.
  • Perform a mail merge using the specified field names and field values using Document.MailMerge.Execute() method.
  • Save the resulting document using Document.SaveToFile() method.

Here is a code example that creates a Word document from a template by performing mail merge using Spire.Doc for Python:

  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()
# Load a Word template with merge fields
document.LoadFromFile("Template_MergeFields.docx")

# Define a list of field names
filedNames = ["Recipient Name", "Company Name", "Amount", "Due Date", "Payment Method", "Sender Name", "Title", "Phone"]

# Define a list of field values
filedValues = ["John Smith",  "ABC Company", "$500", DateTime.get_Now().Date.ToString(), "PayPal", "Sarah Johnson", "Accounts Receivable Manager", "123-456-7890"]

# Perform a mail merge operation using the specified field names and field values
document.MailMerge.Execute(filedNames, filedValues)

# Save the resulting document
document.SaveToFile("CreateDocumentByMailMerge.docx", FileFormat.Docx2016)
document.Close()

Create Word Documents from Templates with Python

Get a Free License

To fully experience the capabilities of Spire.Doc for Python without any evaluation limitations, you can request a free 30-day trial license.

Conclusion

This blog demonstrated how to create Word Documents from templates in 3 different ways using Python and Spire.Doc for Python. In addition to creating Word documents, Spire.Doc for Python provides numerous features for manipulating Word documents, you can check its documentation for more information. If you encounter any questions, please feel free to post them on our forum or send them to our support team via email.

See Also