Font

Font (2)

When working with Word documents, managing fonts can be a tedious task, especially when dealing with large files or multiple documents. Whether you're looking to standardize fonts across a document or fix inconsistencies, knowing how to retrieve and replace fonts efficiently is a valuable skill. In this guide, you will learn how to use Spire.Doc for Python to automate font retrieval and replacement processes.

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 command.

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

Retrieve Fonts in a Word Document

To retrieve font information from a Word document, you will need to iterate through the document's sections, paragraphs, and their child objects. As you check each child object, look for instances of TextRange. If a TextRange is found, you can extract the font details such as the font name and size from its CharacterFormat properties.

The following are the steps to retrieve font information from a Word document using Python:

  • Create a Document object.
  • Load a Word document using the Document.LoadFromFile() method.
  • Iterate through each section and paragraph.
  • For each child object, check if it’s an instance of TextRange.
  • If it is, get the font name and size using the TextRange.CharacterFormat.FontName and TextRange.CharacterFormat.FontSize properties.
  • Python
from spire.doc import *
from spire.doc.common import *

# Function to write string to a txt file
def WriteAllText(fname:str,text:List[str]):
    fp = open(fname,"w")
    for s in text:
        fp.write(s)

# Customize a FontInfo class
class FontInfo:
    def __init__(self):
        self._m_name = ''
        self._m_size = None

    def __eq__(self,other):
        if isinstance(other,FontInfo):
            return self._m_name == other.get_name() and self._m_size == other.get_size()
        return False

    def get_name(self):
        return self._m_name

    def set_name(self, value):
        self._m_name = value

    def get_size(self):
        return self._m_size

    def set_size(self, value):
        self._m_size = value

# Declare variables
fontImformations = ""
font_infos = []

# Create a Document instance
document = Document()

# Load a Word document
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")

# Iterate through the sections
for i in range(document.Sections.Count):

    # Get a specific section
    section = document.Sections.get_Item(i)

    # Iterate through the paragraphs
    for j in range(section.Body.Paragraphs.Count):

        # Get a specific paragraph
        paragraph = section.Body.Paragraphs.get_Item(j)

        # Iterate through the child objects
        for k in range(paragraph.ChildObjects.Count):
            
            # Get a specific paragraph
            obj = paragraph.ChildObjects.get_Item(k)

            # Determine if a child object is a text range
            if isinstance(obj, TextRange):

                # Get a specific text range
                txtRange = obj if isinstance(obj, TextRange) else None
       
                # Get the font name and size
                fontName = txtRange.CharacterFormat.FontName
                fontSize = txtRange.CharacterFormat.FontSize

                # Get text color
                textColor = txtRange.CharacterFormat.TextColor.Name

                # Store the font information in the fontInformations variable
                fontInfo = FontInfo()
                fontInfo.set_name(fontName)
                fontInfo.set_size(fontSize)
                if  fontInfo not in font_infos:
                    font_infos.append(fontInfo)                   
                    str = "Font Name: {0:s}, Size:{1:f}, Color:{2:s}".format(fontInfo.get_name(), fontInfo.get_size(), textColor)
                    fontInformations += str
                    fontInformations += '\r'

# Write font information to a txt file
WriteAllText("output/GetFonts.txt", fontInformations)

# Dispose resources
document.Dispose()

Retrieve fonts used in a Word document

Replace Fonts in a Word Document

Once you retrieve the font name of a specific text range, you can easily replace it with a different font. To do this, utilize the TextRange.CharacterFormat.FontName property to assign a new font. Additionally, you can modify the font size and text color using the corresponding properties in the TextRange class.

The following are the steps to replace a specific font in a Word document using Python:

  • Create a Document object.
  • Load a Word document using the Document.LoadFromFile() method.
  • Iterate through each section and paragraph.
  • For each child object, check if it’s an instance of TextRange.
  • If it is, get the font name using the TextRange.CharacterFormat.FontName property.
  • Check if the font name is the specified font.
  • If it is, set a new font name for the text range using the TextRange.CharacterFormat.FontName property.
  • Save the changes to a different Word file using the Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document instance
document = Document()

# Load a Word document
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")

# Iterate through the sections
for i in range(document.Sections.Count):

    # Get a specific section
    section = document.Sections.get_Item(i)

    # Iterate through the paragraphs
    for j in range(section.Body.Paragraphs.Count):

        # Get a specific paragraph
        paragraph = section.Body.Paragraphs.get_Item(j)

        # Iterate through the child objects
        for k in range(paragraph.ChildObjects.Count):
            
            # Get a specific paragraph
            obj = paragraph.ChildObjects.get_Item(k)

            # Determine if a child object is a text range
            if isinstance(obj, TextRange):

                # Get a specific text range
                txtRange = obj if isinstance(obj, TextRange) else None
       
                # Get the font name
                fontName = txtRange.CharacterFormat.FontName

                # Determine if the font name is Microsoft JhengHei
                if (fontName == "Microsoft JhengHei"):

                    # Replace the font with another font
                    txtRange.CharacterFormat.FontName = "Segoe Print"

# Save the document to a different file
document.SaveToFile("output/ReplaceFonts.docx", FileFormat.Docx)

# Dispose resources
document.Dispose()

Replace a specific font in a Word document

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.

Modifying the font in a Word document can significantly impact its visual appearance and overall readability. Whether you want to enhance the document's style or align it with specific formatting requirements, changing the font is a straightforward process that allows you to customize your text. In this article, you will learn how to change font of a paragraph or a piece of text 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 command.

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

Change the Font of a Paragraph in Python

Using Spire.Doc for Python, you can create a ParagraphStyle object which defines the font information that can be applied to a certain paragraph. The following are the steps to change the font of a paragraph.

  • Create a Document instance.
  • Load a Word document using Document.LoadFromFile() method.
  • Get a specified section through Document.Sections[index] property.
  • Get a specified paragraph that you want to change the font through Section.Paragraphs[index] property.
  • Create a ParagraphStyle instance, specifying the font name, font color and font style through the properties under it.
  • Add the style to the document using Document.Styles.Add() method.
  • Apply the style to the paragraph using Paragraph.ApplyStyle() method.
  • Save the result document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document instance
document = Document()

# Load a Word document
document.LoadFromFile('C:/Users/Administrator/Desktop/input.docx')

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

# Get a specific paragraph
paragraph = section.Paragraphs[2]

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

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

# Save the result document
document.SaveToFile('output/ChangeFontOfParagraph.docx', FileFormat.Docx)

Python: Change the Font of a Word Document

Change the Font of Specific Text in Python

To change the font of specific text (letter, phrase or sentence) in a Word document, you need first to find the text from the document and then set a different color or font style for it. The following are the detailed steps.

  • Create a Document instance.
  • Load a Word document using Document.LoadFromFile() method.
  • Find the text that you want to change font color using Document.FindAllString() method.
  • Loop through all occurrences of the searched text and change the font color or style for each occurrence through the properties under TextSelection.GetAsOneRange().CharacterFormat object.
  • Save the result document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document instance
document = Document()

# Load a Word document
document.LoadFromFile('C:/Users/Administrator/Desktop/input.docx')

# Find the text that you want to change font
textSelections = document.FindAllString('programming language', False, True)

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

# Save the result document
document.SaveToFile('output/ChangeFontOfText.docx', FileFormat.Docx)

Python: Change the Font of a Word Document

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.

page