DEV Community

Jeremy K.
Jeremy K.

Posted on

Change Fonts in a Word Document with Python

Standardizing fonts across multiple Word documents is a common yet tedious task in daily office work. Whether you are preparing corporate reports, cleaning up inconsistent user submissions, or replacing missing fonts to prevent layout shifts, doing this manually—page by page—is inefficient and prone to missing text inside tables, headers, or text boxes.

By programmatically controlling document fonts with Python, you can automate this entire workflow. This guide explores how to use the Free Spire.Doc for Python library to modify font styles efficiently.


Setting Up the Environment

Start by installing the library via pip:

pip install spire.doc.free
Enter fullscreen mode Exit fullscreen mode

Once installed, import the necessary modules into your script:

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

Core Concepts: CharacterFormat and ParagraphStyle

In the Free Spire.Doc object model, all font-related attributes—such as typeface, size, color, bold, and italic—are managed through the CharacterFormat property. Whether you are styling an entire paragraph or tweaking a specific word, your changes ultimately target this CharacterFormat object.

The ParagraphStyle class lets you define reusable custom styles. It includes a CharacterFormat property to control the visual appearance of text. Once you define a style, you add it to the document using Styles.Add() and apply it to any paragraph with ApplyStyle().


Scenario 1: Changing the Font of an Entire Paragraph

When you need to uniformly reformat all the text within a specific paragraph, creating and applying a paragraph style is the cleanest approach.

Code Example

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

# Load the document
doc = Document()
doc.LoadFromFile('Sample.docx')

# Target a specific paragraph (index starts at 0)
section = doc.Sections[0]
paragraph = section.Paragraphs[2]

# Define a new paragraph style
style = ParagraphStyle(doc)
style.Name = 'ParaFont'
style.CharacterFormat.FontName = 'Arial'
style.CharacterFormat.FontSize = 12
style.CharacterFormat.Bold = True
style.CharacterFormat.Italic = True
style.CharacterFormat.TextColor = Color.get_Red()

# Register and apply the style
doc.Styles.Add(style)
paragraph.ApplyStyle(style.Name)

# Save the updated document
doc.SaveToFile('output/ChangeParaFont.docx', FileFormat.Docx)
doc.Dispose()
Enter fullscreen mode Exit fullscreen mode

How It Works

  • ParagraphStyle(doc) initializes a new style container.
  • The CharacterFormat properties define the exact font appearance (name, size, weight, color).
  • ApplyStyle() attaches your custom style to the target paragraph in one go.

This method is ideal for bulk formatting of headings, subheadings, or standard body text.


Scenario 2: Finding and Modifying Specific Text

If you only want to change the font for certain keywords or phrases, use the FindAllString method for precise text targeting.

Code Example

from spire.doc import Document, Color

doc = Document()
doc.LoadFromFile('Sample.docx')

# Locate all occurrences of the target text (case-sensitive)
selections = doc.FindAllString('target text', False, True)

# Update the font for each match
for selection in selections:
    text_range = selection.GetAsOneRange()
    text_range.CharacterFormat.FontName = 'Cambria'
    text_range.CharacterFormat.FontSize = 14
    text_range.CharacterFormat.TextColor = Color.get_Red()
    text_range.CharacterFormat.Bold = True

doc.SaveToFile('output/ChangeTextFont.docx', FileFormat.Docx)
doc.Dispose()
Enter fullscreen mode Exit fullscreen mode

How It Works

  • FindAllString() scans the document and returns a list of TextSelection objects representing the found instances.
  • GetAsOneRange() converts a selection into a TextRange object, allowing direct manipulation of its CharacterFormat.

This approach is perfect for highlighting keywords, updating product names, or correcting specific terminology.


Important Considerations

  • Free Version Limits: The free edition of Spire.Doc is capped at processing 500 paragraphs per document. This is sufficient for most small-to-medium projects and evaluation purposes.

  • Resource Management: Always call Dispose() (or Close()) after saving to properly release system resources and avoid memory leaks.

  • Full Document Overhaul: To change the font of every piece of text in a document, you can iterate through Sections, then Paragraphs, then inspect each ChildObject. Whenever you encounter a TextRange, apply your font changes directly.


Summary

This article demonstrated two practical techniques for modifying fonts in Word documents using Python:

  1. Paragraph-wide changes – using ParagraphStyle for consistent, reusable formatting.
  2. Targeted text changes – using FindAllString to locate and update specific words or phrases.

Both methods operate entirely within Python and do not require Microsoft Office to be installed, making them highly suitable for server-side or automated batch-processing tasks.

Top comments (0)