Embed private font into Word document when save as .docx file format

2016-11-09 08:49:02 Written by  support iceblue
Rate this item
(1 Vote)

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.

Embed private font into Word document when save as .docx file format

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:

Embed private font into Word document when save as .docx file format

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);
        }
    }
}

Additional Info

  • tutorial_title:
Last modified on Friday, 03 September 2021 03:59