DEV Community

Pilalo Jovanitho
Pilalo Jovanitho

Posted on

Tired of Manually Changing Fonts? Try This C# Approach

Developers working with Word documents in C# often face challenges with font inconsistencies, especially in shared or cross-platform environments. Fonts may render differently across Windows, macOS, or Linux, leading to formatting issues in reports, contracts, or templates. Programmatically managing fonts ensures consistency and professionalism.

This article explores practical C# techniques using Spire.Doc for .NET, a lightweight library for server-side Word processing. Learn to find and replace fonts in documents, addressing common pain points like legacy file cleanup or bulk standardization. With .NET 8's enhanced performance, these methods scale efficiently for large files.

Understanding Fonts in Word Documents

Word documents store fonts at multiple levels: document-wide defaults, section styles, paragraph formats, and character runs (TextRanges). Fonts include name, size, style (bold/italic), and color. Embedded fonts travel with the document, while standard ones rely on system availability.

Spire.Doc for .NET simplifies access via the Document.Fonts collection and CharacterFormat properties, outperforming Microsoft Word Interop on servers.

Feature Word Interop Spire.Doc for .NET
License Requires Office Royalty-free license
Server-side safe No (COM threading issues) Yes
Font traversal speed Slow for 100+ page docs 5-10x faster
Embedded font support Limited Full

Tip: Always check Font.IsEmbedded for portable docs.

This foundation enables precise find and replace font operations.

Getting Fonts from Documents

Extracting used fonts reveals inconsistencies. Spire.Doc iterates through sections, paragraphs, and TextRanges to catalog fonts without loading the full UI.

Steps to list fonts:

  1. Load the document: Document doc = new Document("input.docx");
  2. Use a Dictionary<Font, List<TextRange>> to track usages.
  3. Traverse structure:
Dictionary<Font, List<TextRange>> fontRanges = new Dictionary<Font, List<TextRange>>();
foreach (Section section in doc.Sections)
{
    foreach (Paragraph para in section.Paragraphs)
    {
        foreach (DocumentObject obj in para.ChildObjects)
        {
            if (obj.DocumentObjectType == DocumentObjectType.TextRange)
            {
                TextRange range = obj as TextRange;
                Font font = range.CharacterFormat.Font;
                if (!fontRanges.ContainsKey(font))
                    fontRanges[font] = new List<TextRange>();
                fontRanges[font].Add(range);
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode
  1. Output details: Console.WriteLine($"Font: {font.Name}, Size: {font.Size}, Bold: {font.Bold}");

This logs all unique fonts, e.g., "Calibri (Body) 11pt" vs. "Arial 12pt Bold". For large docs (500+ pages), process asynchronously to avoid timeouts—Spire.Doc handles 1GB+ files efficiently.

Handle edge cases: Skip tables (Table objects) or hyperlinks by checking DocumentObjectType.

Replacing Fonts with C

C# Word font replacement standardizes documents, e.g., swap "Times New Roman" for "Calibri" enterprise-wide.

Core method using traversal:

public void ReplaceFont(Document doc, string oldFontName, string newFontName)
{
    foreach (Section section in doc.Sections)
    {
        foreach (Paragraph para in section.Paragraphs)
        {
            foreach (DocumentObject obj in para.ChildObjects.OfType<TextRange>())
            {
                TextRange range = obj as TextRange;
                if (range.CharacterFormat.Font.Name.Equals(oldFontName, StringComparison.OrdinalIgnoreCase))
                {
                    range.CharacterFormat.Font.Name = newFontName;
                }
            }
        }
        // Also update table cells
        foreach (Table table in section.Tables)
        {
            // Similar loop for table cells...
        }
    }
    doc.SaveToFile("output.docx");
}
Enter fullscreen mode Exit fullscreen mode

Batch processing tip: For 100+ files, use Parallel.ForEach with CancellationToken for progress tracking.

Before: Mixed "Arial" and "Helvetica". After: Uniform "Segoe UI".

Advanced Techniques and Performance Tips

For embedded fonts, query doc.EmbeddedFonts and substitute via Font.Substitute.

Bulk ops: Load fonts into a lookup table pre-traversal for O(1) checks.

Performance: On .NET 8, Spire.Doc processes 200-page docs in <2s vs. Interop's 30s.

Handle Unicode: Set CharacterFormat.FontNameAsian for multilingual docs.

Conclusion

Mastering font management in C# with Spire.Doc for .NET resolves formatting woes efficiently. Extract via dictionaries, replace through targeted traversal, and scale with async patterns.

Implement today: Download Spire.Doc trial. Automate workflows amid rising no-code trends—future-proof your .NET apps.

Top comments (0)