Articles in this section
Category / Section

How to find list of used fonts in the Word document?

2 mins read

Syncfusion Essential DocIO is a .NET Word library used to create, read, and edit Word documents programmatically without Microsoft Word or Interop dependencies. Using this library, you can find the list of fonts used in the Word document.

Steps to find the list of fonts used in the Word document programmatically:

  1. Create a new C# console application project.

    Graphical user interface, application

Description automatically generated

  2. Install the Syncfusion.DocIO.Winforms NuGet package as a reference to your .NET Framework applications from NuGet.org.

    Graphical user interface, text, application, email

Description automatically generated

  3. Include the following namespace in the Program.cs file.

C#

using Syncfusion.DocIO;


using Syncfusion.DocIO.DLS;

 

VB.NET

Imports Syncfusion.DocIO


Imports Syncfusion.DocIO.DLS

 

  1. Use the following code example to find the list of fonts used in the Word document.


//Open the template document.


WordDocument wordDocument = new WordDocument(@"../../Data/Adventure.docx", FormatType.Docx);


//Get the list of fonts used in current Word document.


List<Font> usedFontsCollection = GetUsedFontsList(wordDocument);


Console.WriteLine("List of fonts used in the Word document:");


foreach (Font usedFont in usedFontsCollection)


{


Console.WriteLine("Font name : " + usedFont.Name + "; Bold : " + usedFont.Bold + "; Italic : " + usedFont.Italic);


}


//Save word document.


wordDocument.Save("Output.docx");


wordDocument.Close();


Console.WriteLine("Press enter key to exit.");


Console.ReadKey();

VB.NET

' Open the template document.


Dim wordDocument As New WordDocument("../../Data/Adventure.docx", FormatType.Docx)


' Get the list of fonts used in the current Word document.


Dim usedFontsCollection As List(Of Font) = GetUsedFontsList(wordDocument)


Console.WriteLine("List of fonts used in the Word document:")


For Each usedFont As Font In usedFontsCollection


Console.WriteLine("Font name : " & usedFont.Name & "; Bold : " & usedFont.Bold & "; Italic : " & usedFont.Italic)


Next


' Save the Word document.


wordDocument.Save("Output.docx")


wordDocument.Close()


Console.WriteLine("Press enter key to exit.")


Console.ReadKey()

 

  1. Helper methods.C#
/// <summary>

/// Get the List of fonts which is used in current Word document.

​/// </summary>

​/// <param name="document">Word document</param>

​/// <returns>Used font collection</returns>

​private static List<Font> GetUsedFontsList(WordDocument document)

​{

​ List<Font> usedFonts = new List<Font>();

​​    Font font = null;

​    //Visits all document entities.

​    foreach (dynamic item in document.Visit())

​    {

​     // Gets the font from CharacterFormat or BreakCharacterFormat.

​        font = HasProperty(item, "CharacterFormat") ? item.CharacterFormat.Font :

​                (HasProperty(item, "BreakCharacterFormat") ? item.BreakCharacterFormat.Font : null);

        AddToFontsCollection(font, usedFonts);
​        //Gets the font from ListFormat.
​        GetUsedFontFromListFormat(item, usedFonts);
​    }
    return usedFonts;
​}

​/// <summary>

​/// Add the font to the collection.

​/// </summary>

​/// <param name="font">Font to add.</param>

​/// <param name="usedFonts">Collection of fonts.</param>

private static void AddToFontsCollection(Font font, List<Font> usedFonts)

​{

​ // Check whether the font is different in name and font style properties and add it to the collection.

​    if (font != null && font is Font &&

​       !(usedFonts.Find((match) => match.Name == font.Name && match.Italic == font.Italic && match.Bold == font.Bold) is

Font))

​    {
​     usedFonts.Add(font);

​    }

​}

​/// <summary>

​/// Gets the fonts used in the List Format.

​/// </summary>

​/// <param name="item">Current item.</param>

​/// <param name="usedFonts">Collection of fonts.</param>

​/// <returns></returns>

​private static void GetUsedFontFromListFormat(dynamic item, List<Font> usedFonts)

​{

​ if (item is WParagraph)

​    {

​     //if item is a paragraph then get the font from list format.

​        if (item.ListFormat != null && item.ListFormat.CurrentListLevel != null)

​        {

​         Font font = item.ListFormat.CurrentListLevel.CharacterFormat.Font;

​            AddToFontsCollection(font, usedFonts);

​     }

​    }

​}

​/// <summary>

​/// Check whether the property is available in the object.

​/// </summary>

​/// <param name="obj">Current object.</param>

​/// <param name="name">Property to check.</param>

​/// <returns>True, if object has property. Otherwise, false.</returns>

​private static bool HasProperty(dynamic obj, string name)

​{

​ Type objType = obj.GetType();

​    return objType.GetProperty(name) != null;

​}


 

VB.NET

''' <summary>

''' Get the List of fonts which is used in the current Word document.

''' </summary>

''' <param name="document">Word document</param>

''' <returns>Used font collection</returns>

Private Function GetUsedFontsList(ByVal document As WordDocument) As List(Of Font)

Dim usedFonts As New List(Of Font)()

    Dim font As Font = Nothing
    ' Visits all document entities.

    For Each item As Object In document.Visit()


     ' Gets the font from CharacterFormat or BreakCharacterFormat.


        font = If(HasProperty(item, "CharacterFormat"), item.CharacterFormat.Font,


               If(HasProperty(item, "BreakCharacterFormat"), item.BreakCharacterFormat.Font, Nothing))


        AddToFontsCollection(font, usedFonts)


        ' Gets the font from ListFormat.


        GetUsedFontFromListFormat(item, usedFonts)


    Next


    Return usedFonts


End Function



''' <summary>


''' Add the font to the collection.


''' </summary>


''' <param name="font">Font to add.</param>


''' <param name="usedFonts">Collection of fonts.</param>


Private Sub AddToFontsCollection(ByVal font As Font, ByVal usedFonts As List(Of Font))


    ' Check whether the font is different in name and font style properties and add it to the collection.


    If font IsNot Nothing AndAlso TypeOf font Is Font AndAlso


   Not usedFonts.Any(Function(match) match.Name = font.Name AndAlso match.Italic = font.Italic AndAlso match.Bold = font.Bold) Then


        usedFonts.Add(font)


   End If


End Sub



''' <summary>


''' Gets the fonts used in the List Format.


''' </summary>


''' <param name="item">Current item.</param>


''' <param name="usedFonts">Collection of fonts.</param>


Private Sub GetUsedFontFromListFormat(ByVal item As Object, ByVal usedFonts As List(Of Font))


If TypeOf item Is WParagraph Then


     ' If the item is a paragraph, then get the font from the list format.


        Dim paragraph As WParagraph = DirectCast(item, WParagraph)


        If paragraph.ListFormat IsNot Nothing AndAlso paragraph.ListFormat.CurrentListLevel IsNot Nothing Then


         Dim font As Font = paragraph.ListFormat.CurrentListLevel.CharacterFormat.Font


            AddToFontsCollection(font, usedFonts)


        End If


    End If


End Sub



''' <summary>


''' Check whether the property is available in the object.


''' </summary>


''' <param name="obj">Current object.</param>


''' <param name="name">Property to check.</param>


''' <returns>True, if object has property. Otherwise, false.</returns>


Private Function HasProperty(ByVal obj As Object, ByVal name As String) As Boolean


    Dim objType As Type = obj.GetType()


    Return objType.GetProperty(name) IsNot Nothing


End Function





 

  1. Helper Class

C#

public static class DocIOExtensions
{
    public static IEnumerable<IEntity> Visit(this ICompositeEntity entity)
    {
        var entities = new Stack<IEntity>(new IEntity[] { entity });
        while (entities.Count > 0)
        {
            var e = entities.Pop();
            yield return e;
            if (e is ICompositeEntity)
            {
                foreach (IEntity childEntity in ((ICompositeEntity)e).ChildEntities)
                {
                    entities.Push(childEntity);
                }
            }
        }
    }
}

 

VB.NET

Public Module DocIOExtensions
<Extension()>
Public Iterator Function Visit(ByVal entity As ICompositeEntity) As IEnumerable(Of IEntity)
    Dim entities = New Stack(Of IEntity)(New IEntity() {entity})
    While entities.Count > 0
        Dim e = entities.Pop()
        Yield e
        If TypeOf e Is ICompositeEntity Then
            For Each childEntity As IEntity In CType(e, ICompositeEntity).ChildEntities
                entities.Push(childEntity)
            Next
        End If
    End While
End Function
End Module

 

A complete working sample to find the list of fonts used in the Word document using C# can be downloaded from GitHub.

Take a moment to peruse the document where you can find basic Word document processing options along with the features like mail merge, merge and split documents, find and replace text in the Word document, protect the Word documents, and most importantly, the PDF and Image conversions with code examples.

Explore more about the rich set of Syncfusion Word Framework features.


 

Conclusion

I hope you enjoyed learning about how to find list of used fonts in the Word document.

You can refer to our WinForms DocIO feature tour page to know about its other groundbreaking feature representations. You can also explore our WinForms DocIO documentation to understand how to create and manipulate data.

For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.

If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forumsDirect-Trac, or feedback portal. We are always happy to assist you!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please sign in to leave a comment
Access denied
Access denied