DEV Community

jelizaveta
jelizaveta

Posted on

Modifying or Replacing Fonts in Word Using Python

In daily office work, adjusting fonts in Word documents is a frequent need—whether it's unifying report styles, highlighting key information, or batch-processing large numbers of documents, manual operations are often inefficient. This article introduces how to use the Spire.Doc for Python library to efficiently modify font styles in Word documents programmatically.

1. Environment Setup

First, install Spire.Doc for Python via pip:

pip install Spire.Doc
Enter fullscreen mode Exit fullscreen mode

After installation, import the required modules in your Python script:

from spire.doc import *
from spire.doc.common import *
Enter fullscreen mode Exit fullscreen mode

2. Method 1: Modifying the Font of an Entire Paragraph

When you need to uniformly adjust the font of all text in a specific paragraph, you can achieve this by creating a paragraph style and applying it to the target paragraph.

Core steps : Load document → Get target paragraph → Create paragraph style → Set font properties → Apply style → Save document.

from spire.doc import *
from spire.doc.common import *

# Create a Document instance
document = Document()

# Load a Word document
document.LoadFromFile('input.docx')

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

# Get a specific paragraph (index starts from 0)
paragraph = section.Paragraphs[2]

# Create a paragraph style
style = ParagraphStyle(document)
style.Name = 'NewStyle'
style.CharacterFormat.Bold = True          # Bold
style.CharacterFormat.Italic = True        # Italic
style.CharacterFormat.TextColor = Color.get_Red()   # Red color
style.CharacterFormat.FontName = 'Cambria' # Font name
document.Styles.Add(style)

# Apply the style to the paragraph
paragraph.ApplyStyle(style.Name)

# Save the result document
document.SaveToFile('ChangeFontOfParagraph.docx', FileFormat.Docx)
Enter fullscreen mode Exit fullscreen mode

Code explanation :

  • The ParagraphStyle class is used to create custom paragraph styles, where the CharacterFormat property controls font name, size, color, bold, italic, and other formatting.
  • Styles.Add() adds the style to the document's style collection.
  • The ApplyStyle() method applies the style to the specified paragraph.

This approach is suitable for uniform formatting of entire paragraphs , such as unifying the font style of headings or body text paragraphs.

3. Method 2: Finding Specific Text and Modifying Its Font

When you only need to change the font of certain keywords or phrases in the document, you can use the text search feature to precisely locate them.

Core steps : Load document → Search for target text → Iterate through matches → Modify font properties → Save document.

from spire.doc import *
from spire.doc.common import *

# Create a Document instance
document = Document()

# Load a Word document
document.LoadFromFile('input.docx')

# Search for specified text (third parameter True means case-sensitive)
textSelections = document.FindAllString('programming language', False, True)

# Modify the font style of the found text
for selection in textSelections:
    selection.GetAsOneRange().CharacterFormat.TextColor = Color.get_Red()
    selection.GetAsOneRange().CharacterFormat.Bold = True

# Save the result document
document.SaveToFile('ChangeFontOfText.docx', FileFormat.Docx)
Enter fullscreen mode Exit fullscreen mode

Code explanation :

  • The FindAllString() method finds all matching text in the document and returns a list of TextSelection objects.
  • GetAsOneRange() converts the found text into a TextRange object.
  • Through the CharacterFormat property, you can finely control font color, bold, font size, etc.

This approach is suitable for keyword highlighting or specific term formatting , as it is precise and does not affect other text.

4. Comparison of the Two Methods

Comparison Dimension Method 1 (Paragraph Style) Method 2 (Text Search)
Scope Entire paragraph Specific text fragments
Use case Uniform paragraph formatting Keyword highlighting, term annotation
Flexibility Medium High
Preserves original styles? Replaces entire paragraph style Modifies only font properties, preserves other formatting

5. Summary

With Spire.Doc for Python, we can easily achieve programmatic control over font styles in Word documents. Whether it's uniformly formatting entire paragraphs via paragraph styles, or precisely locating and modifying specific words through text search, both approaches can greatly improve document processing efficiency. Once you master these two methods, you can flexibly choose the appropriate one based on your actual needs, leaving repetitive font adjustment tasks to be automatically handled by code.

Top comments (0)