C# 如何将未安装字体从字体文件嵌入到Word文档

有时候我们会遇到这样一种情况,我们的文档在别人的电脑上打开后,字体变成了乱码,这是因为别人的电脑上没有安装我们的文档中所使用的字体。那如何避免这种情况发生呢?有两种解决方案,一是在别人的电脑上安装这种字体,二是将该字体内嵌到Word文档中。无疑第二种方案比第一种要好。这篇文章我将介绍如何使用C#及.NET Word组件Spire.Doc将未安装字体从字体文件嵌入到Word文档。

以下是一种特殊字体的截图,我没有将它安装在我的电脑上,接下来我将把它内嵌到word文档中,并使用它来创建文本。



首先下载组件并安装,安装以后将Spire.Doc.dll文件添加到项目作为引用并添加命名空间。

核心代码及步骤如下:

步骤1: 创建一个空白的Word文档。

Document document = new Document();

步骤2: 添加一个节和一个段落到文档。

Section section = document.AddSection();
Paragraph p = section.AddParagraph();

步骤3: 添加文本到段落,并为文本设置字体名称和字体大小。这里的字体名称就是嵌入的字体名称。

TextRange range = p.AppendText("Letlife be beautiful like summer flowers\n"
    +"Life, thin and light-off time and timeagain\n"
    + "Frivolous tireless");
range.CharacterFormat.FontName = "DeeDeeFlowers";
range.CharacterFormat.FontSize = 20;

步骤4: 为了使字体成功的嵌入到文档,我们需要将EmbedFontsInFile属性的布尔值设置为true。

document.EmbedFontsInFile = true;

步骤5: 将字体从文件嵌入到Word文档中。

document.PrivateFontList.Add(newPrivateFontPath("DeeDeeFlowers",@"E:\Program Files\DeeDeeFlowers.ttf"));  

步骤6: 保存为.docx 格式。

document.SaveToFile("result.docx",FileFormat.Docx);

效果图:




完整代码:

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
 
namespace Embed_private_font_into_Word
{
    class Program
    {
        static voidMain(string[] args)
        {
            Documentdocument = 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(newPrivateFontPath("DeeDeeFlowers", @"E:\ProgramFiles\DeeDeeFlowers.ttf"));  
 
           document.SaveToFile("result.docx", FileFormat.Docx);
        }
    }
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值