C#: Get and Replace Fonts in Word Documents
Fonts play a crucial role in defining the visual appeal and readability of Word documents, influencing everything from professional reports to creative projects. Whether you're looking to refresh the design of your document by replacing outdated fonts or troubleshooting missing fonts that disrupt formatting, understanding how to retrieve and replace fonts in Microsoft Word is an essential skill.
In this article, you will learn how to get and replace fonts in a Word document using C# and Spire.Doc for .NET.
Install Spire.Doc for .NET
To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.Doc
Get Fonts Used in a Word Document in C#
To extract font information from a Word document, you must traverse its sections and paragraphs, examining each child object within the paragraphs. If a child object is identified as a TextRange, you can retrieve the font details—such as the font name, size, and color—using the properties of the TextRange class.
The following are the steps to get fonts used in a Word document in C#:
- Create a Document object.
- Load a Word document using the Document.LoadFromFile() method.
- Iterate through each section, paragraph, and child object.
- For each child object, check if it is an instance of TextRange class.
- If it is, retrieve the font name and size using the TextRange.CharacterFormat.FontName and TextRange.CharacterFormat.FontSize properties.
- Write the font information in a text file.
- C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
namespace RetrieveFonts
{
// Customize a FontInfo class to help store font information
class FontInfo
{
public string Name { get; set; }
public float? Size { get; set; }
public FontInfo()
{
Name = "";
Size = null;
}
public override bool Equals(object obj)
{
if (this == obj) return true;
if (!(obj is FontInfo other)) return false;
return Name.Equals(other.Name) && Size.Equals(other.Size);
}
public override int GetHashCode()
{
return HashCode.Combine(Name, Size);
}
}
class Program
{
// Function to write string to a txt file
static void WriteAllText(string filename, List<string> text)
{
try
{
using (StreamWriter writer = new StreamWriter(filename))
{
foreach (var line in text)
{
writer.WriteLine(line);
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
static void Main(string[] args)
{
List<FontInfo> fontInfos = new List<FontInfo>();
List<string> fontInformations = new List<string>();
// Create a Document instance
Document document = new Document();
// Load a Word document
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx");
// Iterate through the sections
foreach (Section section in document.Sections)
{
// Iterate through the paragraphs
foreach (Paragraph paragraph in section.Body.Paragraphs)
{
// Iterate through the child objects
foreach (DocumentObject obj in paragraph.ChildObjects)
{
if (obj is TextRange txtRange)
{
// Get the font name, size and text color
string fontName = txtRange.CharacterFormat.FontName;
float fontSize = txtRange.CharacterFormat.FontSize;
string textColor = txtRange.CharacterFormat.TextColor.ToString();
// Store the font information
FontInfo fontInfo = new FontInfo { Name = fontName, Size = fontSize };
if (!fontInfos.Contains(fontInfo))
{
fontInfos.Add(fontInfo);
string str = $"Font Name: {fontInfo.Name}, Size: {fontInfo.Size:F2}, Color: {textColor}";
fontInformations.Add(str);
}
}
}
}
}
// Write font information to a txt file
WriteAllText("GetFonts.txt", fontInformations);
// Dispose resources
document.Dispose();
}
}
}

Replace a Specific Font in a Word Document in C#
After retrieving the font name from a specific TextRange, you can easily replace it with a new font using the TextRange.CharacterFormat.FontName property. Additionally, you can modify the font size and text color by accessing the corresponding properties in the TextRange class. This allows for comprehensive customization of the text formatting within the document.
The following are the steps to replace a specific font in a Word document in C#:
- Create a Document object.
- Load a Word document using the Document.LoadFromFile() method.
- Iterate through each section and its paragraphs.
- For each paragraph, check each child object to see if it is an instance of the TextRange class.
- If it is a TextRange, retrieve the font name using the TextRange.CharacterFormat.FontName property.
- Compare the font name to the specified font.
- If they match, set a new font name using the TextRange.CharacterFormat.FontName property.
- Save the modified document to a new Word file using the Document.SaveToFile() method.
- C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
namespace ReplaceFont
{
class Program
{
static void Main(string[] args)
{
// Create a Document instance
Document document = new Document();
// Load a Word document
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx");
// Iterate through the sections
foreach (Section section in document.Sections)
{
// Iterate through the paragraphs
foreach (Paragraph paragraph in section.Body.Paragraphs)
{
// Iterate through the child objects
foreach (DocumentObject obj in paragraph.ChildObjects)
{
// Determine if a child object is a TextRange
if (obj is TextRange txtRange)
{
// Get the font name
string fontName = txtRange.CharacterFormat.FontName;
// Determine if the font name is Calibri
if (fontName.Equals("Calibri", StringComparison.OrdinalIgnoreCase))
{
// Replace the font with another font
txtRange.CharacterFormat.FontName = "Segoe Print";
}
}
}
}
}
// Save the document to a different file
document.SaveToFile("ReplaceFont.docx", FileFormat.Docx);
// Dispose resources
document.Dispose();
}
}
}

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.
Embed private font into Word document when save as .docx file format
Now Spire.Doc supports to embed private fonts from font files into Word document when save as .docx file format. This article will show you the detail steps of how to accomplish this task by using Spire.Doc.
For demonstration, we used a font file DeeDeeFlowers.ttf.

In the following part, we will embed font from above file into a Word document and use it to create text.
Step 1: Create a blank Word document.
Document document = new Document();
Step 2: Add a section and a paragraph to the document.
Section section = document.AddSection(); Paragraph p = section.AddParagraph();
Step 3: Append text to the paragraph, then set the font name and font size for the text.
TextRange range = p.AppendText("Let life be beautiful like summer flowers\n"
+"Life, thin and light-off time and time again\n"
+ "Frivolous tireless");
range.CharacterFormat.FontName = "DeeDeeFlowers";
range.CharacterFormat.FontSize = 20;
Step 4: Allow embedding font in document by setting the Boolean value of EmbedFontsInFile property to true.
document.EmbedFontsInFile = true;
Step 5: Embed private font from font file into the document.
document.PrivateFontList.Add(new PrivateFontPath("DeeDeeFlowers", @"E:\Program Files\DeeDeeFlowers.ttf"));
Step 6: Save as .docx file format.
document.SaveToFile("result.docx", FileFormat.Docx);
After running the code, we'll get the following output:

Full code:
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
namespace Embed_private_font_into_Word
{
class Program
{
static void Main(string[] args)
{
Document document = new Document();
Section section = document.AddSection();
Paragraph p = section.AddParagraph();
TextRange range = p.AppendText("Let life be beautiful like summer flowers\n"
+"Life, thin and light-off time and time again\n"
+ "Frivolous tireless");
range.CharacterFormat.FontName = "DeeDeeFlowers";
range.CharacterFormat.FontSize = 20;
document.EmbedFontsInFile = true;
document.PrivateFontList.Add(new PrivateFontPath("DeeDeeFlowers", @"E:\Program Files\DeeDeeFlowers.ttf"));
document.SaveToFile("result.docx", FileFormat.Docx);
}
}
}
Embed uninstalled fonts by font document when convert word to PDF
We have already shown you how to use uninstalled font by font document when converting word to PDF. Now starts from Spire.Doc 5.6.3, Spire.Doc newly supports to set the font styles for the uninstalled fonts when convert word documents to PDF. Here comes to the code snippets of how to set the font styles for embed the uninstalled fonts by font documents:
Note: Before Start, please download the latest version of Spire.XLS and add Spire.xls.dll in the bin folder as the reference of Visual Studio.
Step 1: Create a new workbook and load from file.
Document document = new Document();
document.LoadFromFile("Testing.docx");
Step 2: Create an instance for class ToPdfParameterList named parms.
ToPdfParameterList parms = new ToPdfParameterList();
Step 3: Define the path of the uninstalled fonts.
{
new PrivateFontPath("Century Gothic",FontStyle.Regular,"fonts\\GOTHIC.TTF"),
new PrivateFontPath("Century Gothic",FontStyle.Bold,"fonts\\GOTHICB.TTF"),
new PrivateFontPath("Century Gothic",FontStyle.Italic,"fonts\\GOTHICI.TTF") ,
new PrivateFontPath("Century Gothic",FontStyle.Bold|FontStyle.Italic,"fonts\\GOTHICBI.TTF")
};
Step 4: Save the document to file and launch to preview it.
document.SaveToFile("Testing.pdf", parms);
System.Diagnostics.Process.Start("Testing.pdf");
Effective screenshot of the embedded uninstalled fonts by setting the font style after converts to PDF:

How to use uninstalled font when converting Doc to PDF via Spire.Doc
Now Spire.Doc support using uninstalled font when converting Doc to PDF to diversity text content. In this article, we'll talk about how to realize this function:
Step 1: Download a font uninstalled in system.

Step 2: Create a new blank Word document.
Document document = new Document();
Step 3: Add a section and create a new paragraph.
Section section = document.AddSection(); Paragraph paragraph = section.Paragraphs.Count > 0 ? section.Paragraphs[0] : section.AddParagraph();
Step 4: Append text for a txtRange.
TextRange txtRange = paragraph.AppendText(text);
Step 5: Create an example for class ToPdfParameterList named to pdf, and create a new PrivateFontPathlist for property PrivateFontPaths, instantiate one PrivateFontPath with name and path of downloaded font.
ToPdfParameterList toPdf = new ToPdfParameterList()
{
PrivateFontPaths = new List()
{
new PrivateFontPath("DeeDeeFlowers",@"D:\DeeDeeFlowers.ttf")
}
};
Step 6: Set the new font for the txtaRange.
txtRange.CharacterFormat.FontName = "DeeDeeFlowers";
Step 7: Convert the Doc to PDF.
document.SaveToFile("result.pdf", toPdf);
Step 8: Review converted PDF files.
System.Diagnostics.Process.Start("result.pdf");
Result screenshot:

Full Code Below:
Document document = new Document();
//Add the first secition
Section section = document.AddSection();
//Create a new paragraph and get the first paragraph
Paragraph paragraph
= section.Paragraphs.Count > 0 ? section.Paragraphs[0] : section.AddParagraph();
//Append Text
String text
= "This paragraph is demo of text font and color. "
+ "The font name of this paragraph is Tahoma. "
+ "The font size of this paragraph is 20. "
+ "The under line style of this paragraph is DotDot. "
+ "The color of this paragraph is Blue. ";
TextRange txtRange = paragraph.AppendText(text);
//Import the font
ToPdfParameterList toPdf = new ToPdfParameterList()
{
PrivateFontPaths = new List<PrivateFontPath>()
{
new PrivateFontPath("DeeDeeFlowers",@"D:\DeeDeeFlowers.ttf")
}
};
//Make use of the font.
txtRange.CharacterFormat.FontName = "DeeDeeFlowers";
document.SaveToFile("result.pdf", toPdf);
System.Diagnostics.Process.Start("result.pdf");
C#: Set Fonts when Creating a New Word Document
When creating a new Word document, setting the appropriate fonts is crucial for establishing tone and enhancing readability. Fonts influence how your content is perceived, whether for formal reports, creative projects, or casual notes. By selecting the right typeface and size, you can ensure your document is not only visually appealing but also effective in communicating your message.
In this article, you will learn how to set fonts when creating a new Word document in C# using Spire.Doc for .NET.
- Set the Font for a Paragraph in C#
- Apply Different Fonts to Text in C#
- Use a Custom Font in a Word Document in C#
Install Spire.Doc for .NET
To begin with, you need to add the DLL files included in the Spire.Doc for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.Doc
Set the Font for a Paragraph in C#
Setting fonts is a fundamental task when working with Word documents in C#. Spire.Doc offers the ParagraphStyle class, which lets you specify font family, size, style, and text color. Once you've created a style, you can apply it to format a paragraph with the desired settings.
The detailed steps to set the font for a paragraph using C# are as follows:
- Create a Document object.
- Add a section and a paragraph to the document.
- Append text to the paragraph.
- Create a ParagraphStyle object.
- Get the CharacterFormat object through the ParagraphStyle.CharacterFormat property.
- Set the font style, name, size and text color using the properties under the CharacterFormat object.
- Add the style to the document using the Document.Styles.Add() method.
- Apply the defined style to the paragraph using the Paragraph.ApplyStyle() method.
- Save the document to a Word file.
Here is an example that demonstrates how to set the font for a paragraph when creating a new Word document in C#:
- C#
using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;
namespace SetFontForParagraph
{
class Program
{
static void Main(string[] args)
{
// Create a Document object
Document doc = new Document();
// Add a section
Section section = doc.AddSection();
// Set the page margins
section.PageSetup.Margins.All = 40f;
// Add a paragraph
Paragraph paragraph = section.AddParagraph();
// Append text to the paragraph
paragraph.AppendText("Spire.Doc for .NET is a powerful library designed for developers " +
"working with document processing in the .NET environment. It enables users to create, " +
"read, modify, and convert various types of document formats, such as DOC, DOCX, PDF, " +
"and more, without the need for Microsoft Office installed on the machine.");
// Create a ParagraphStyle object
ParagraphStyle style = new ParagraphStyle(doc);
// Set the style name
style.Name = "myStyle";
// Set the font style, name, size and text color
style.CharacterFormat.Bold = false;
style.CharacterFormat.TextColor = Color.Black;
style.CharacterFormat.FontName = "Times New Roman";
style.CharacterFormat.FontSize = 14;
// Add the style the document
doc.Styles.Add(style);
// Apply the style to the paragraph
paragraph.ApplyStyle(style.Name);
// Set the horizontal alignment
paragraph.Format.HorizontalAlignment = HorizontalAlignment.Left;
// Save the document to a docx file
doc.SaveToFile("SetFont.docx", FileFormat.Docx2019);
// Dispose resources
doc.Dispose();
}
}
}

Apply Different Fonts to Text in C#
In some cases, you may need to apply various fonts to different segments of the same paragraph. Spire.Doc offers the TextRange class, which allows you to assign distinct styles to specific text ranges within a paragraph. To do this, ensure that the text requiring different styles is organized into separate text ranges.
The steps to apply multiple fonts in a paragraph using C# are as follows:
- Create a Document object.
- Add a section and a paragraph to the document.
- Append text to the paragraph using the Paragraph.AppendText() method, which returns a TextRange object.
- Append more text that needs to be styled differently to the paragraph and return different TextRange objects.
- Create a ParagraphStyle object with the basic font information and apply it to the paragraph.
- Change the font name, style, size and text color of the specified text range using the properties under the specific TextRange object.
- Save the document to a Word file.
Here's an example that demonstrates how to apply different fonts to different parts of a paragraph:
- C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;
namespace ApplyDifferentFontsToText
{
class Program
{
static void Main(string[] args)
{
// Create a Document object
Document doc = new Document();
// Add a section
Section section = doc.AddSection();
// Set the page margins
section.PageSetup.Margins.All = 40f;
// Add a paragraph
Paragraph paragraph = section.AddParagraph();
// Append text to the paragraph
TextRange textRange1 = paragraph.AppendText("Spire.Doc for .NET");
TextRange textRange2 = paragraph.AppendText(" is a powerful library designed for developers " +
"working with document processing in the .NET environment. It enables users to ");
TextRange textRange3 = paragraph.AppendText("create, read, modify, and convert");
TextRange textRange4 = paragraph.AppendText(" various types of document formats, such as ");
TextRange textRange5 = paragraph.AppendText("DOC, DOCX, PDF");
TextRange textRange6 = paragraph.AppendText(" and more, without the need for Microsoft Office installed on the machine.");
// Create a ParagraphStyle object
ParagraphStyle style = new ParagraphStyle(doc);
// Set the style name
style.Name = "myStyle";
// Set the font style, name, size and text color
style.CharacterFormat.Bold = false;
style.CharacterFormat.TextColor = Color.Black;
style.CharacterFormat.FontName = "Times New Roman";
style.CharacterFormat.FontSize = 14;
// Add the style the document
doc.Styles.Add(style);
// Apply the style to the paragraph
paragraph.ApplyStyle(style.Name);
// Change the font style of the specified text ranges
textRange1.CharacterFormat.Bold = true;
textRange1.CharacterFormat.TextColor = Color.Purple;
textRange3.CharacterFormat.Bold = true;
textRange3.CharacterFormat.TextColor = Color.Purple;
textRange5.CharacterFormat.Bold = true;
textRange5.CharacterFormat.TextColor = Color.Purple;
// Set the horizontal alignment
paragraph.Format.HorizontalAlignment = HorizontalAlignment.Left;
// Save the document to a docx file
doc.SaveToFile("ApplyDifferentFonts.docx", FileFormat.Docx2019);
// Dispose resources
doc.Dispose();
}
}
}

Use a Custom Font in a Word Document in C#
Spire.Doc supports custom fonts, allowing you to use fonts that are not installed on the system where the application is running. To use a custom font, you need to embed the font file in your application and then specify it in your code.
The steps to utilize custom fonts in a Word document are as follows:
- Create a Document object.
- Add a section and a paragraph to the document.
- Append text to the paragraph.
- Set the custom fonts for the document using the Document.SetCustomFonts() method.
- Embed fonts in the generated file by setting the Document.EmbedFontsInFile property to true.
- Create a ParagraphStyle object.
- Set the font name to your custom font using the ParagraphStyle.CharacterFormat.FontName property.
- Apply the style to the paragraph using the Paragraph.ApplyStyle() method.
- Save the document to a Word file.
Here's an example that demonstrates how to use a custom font:
- C#
using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;
namespace SetFontForParagraph
{
class Program
{
static void Main(string[] args)
{
// Create a Document object
Document doc = new Document();
// Add a section
Section section = doc.AddSection();
// Set the page margins
section.PageSetup.Margins.All = 40f;
// Add a paragraph
Paragraph paragraph = section.AddParagraph();
// Append text to the paragraph
paragraph.AppendText("Spire.Doc for .NET is a powerful library designed for developers " +
"working with document processing in the .NET environment. It enables users to create, " +
"read, modify, and convert various types of document formats, such as DOC, DOCX, PDF, " +
"and more, without the need for Microsoft Office installed on the machine.");
// Specify the private font path
string fontPath = "C:\\Users\\Administrator\\Desktop\\Super Morning.ttf";
// Create an array of Stream objects to hold the font streams
Stream[] fontStreams = new Stream[1];
fontStreams[0] = new FileStream(fontPath, FileMode.Open, FileAccess.Read);
// Set the custom fonts for the document
doc.SetCustomFonts(fontStreams);
// Embed fonts in the generated file
doc.EmbedFontsInFile = true;
// Create a ParagraphStyle object
ParagraphStyle style = new ParagraphStyle(doc);
// Set the paragraph style name
style.Name = "myStyle";
// Set the font name as the name of the private font
style.CharacterFormat.FontName = "Super Morning";
// Set the font style, size and text color
style.CharacterFormat.Bold = false;
style.CharacterFormat.TextColor = Color.Black;
style.CharacterFormat.FontSize = 14;
// Add the style the document
doc.Styles.Add(style);
// Apply the defined style to the paragraph
paragraph.ApplyStyle(style.Name);
// Set the horizontal alignment
paragraph.Format.HorizontalAlignment = HorizontalAlignment.Left;
// Save the document to a docx file
doc.SaveToFile("UseCustomFont.docx", FileFormat.Docx2019);
// Dispose resources
doc.Dispose();
}
}
}

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.
C#/VB.NET: Change Font Color in Word
If you want to emphasize a specific paragraph or text in your Word document, you can change its font color. This article will demonstrate how to change font color in Word in C# and VB.NET using Spire.Doc for .NET library.
Install Spire.Doc for .NET
To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.Doc
Change Font Color of a Paragraph in C# and VB.NET
The following are the steps to change the font color of a paragraph in a Word document:
- Create a Document instance.
- Load the Word document using Document.LoadFromFile() method.
- Get the desired section using Document.Sections[sectionIndex] property.
- Get the desired paragraph that you want to change the font color of using Section.Paragraphs[paragraphIndex] property.
- Create a ParagraphStyle instance.
- Set the style name and font color using ParagraphStyle.Name and ParagraphStyle.CharacterFormat.TextColor properties.
- 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.
- C#
- VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;
namespace ChangeFontColorForParagraph
{
class Program
{
static void Main(string[] args)
{
//Create a Document instance
Document document = new Document();
//Load a Word document
document.LoadFromFile("Sample.docx");
//Get the first section
Section section = document.Sections[0];
//Change text color of the first Paragraph
Paragraph p1 = section.Paragraphs[0];
ParagraphStyle s1 = new ParagraphStyle(document);
s1.Name = "Color1";
s1.CharacterFormat.TextColor = Color.RosyBrown;
document.Styles.Add(s1);
p1.ApplyStyle(s1.Name);
//Change text color of the second Paragraph
Paragraph p2 = section.Paragraphs[1];
ParagraphStyle s2 = new ParagraphStyle(document);
s2.Name = "Color2";
s2.CharacterFormat.TextColor = Color.DarkBlue;
document.Styles.Add(s2);
p2.ApplyStyle(s2.Name);
//Save the result document
document.SaveToFile("ChangeParagraphTextColor.docx", FileFormat.Docx);
}
}
}

Change Font Color of a Specific Text in C# and VB.NET
The following are the steps to change the font color of a specific text in a Word document:
- Create a Document instance.
- Load a Word document using Document.LoadFromFile() method.
- Find the text that you want to change font color of using Document.FindAllString() method.
- Loop through all occurrences of the searched text and change the font color for each occurrence using TextSelection.GetAsOneRange().CharacterFormat.TextColor Property.
- Save the result document using Document.SaveToFile() method.
- C#
- VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;
namespace ChangeFontColorForText
{
class Program
{
static void Main(string[] args)
{
//Create a Document instance
Document document = new Document();
//Load a Word document
document.LoadFromFile("Sample.docx");
//Find the text that you want to change font color for
TextSelection[] text = document.FindAllString("Spire.Doc for .NET", false, true);
//Change the font color for the searched text
foreach (TextSelection seletion in text)
{
seletion.GetAsOneRange().CharacterFormat.TextColor = Color.Red;
}
//Save the result document
document.SaveToFile("ChangeCertainTextColor.docx", FileFormat.Docx);
}
}
}

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.