前面我们介绍了如何使用Spire.Doc为整个word文档添加背景色,Spire.Doc也支持为word文档中特定的某段落或某文添加底纹背景,以达到美化文档和突出显示文档内容的效果。该文将详细介绍如何使用C#为word文档中指定的段落或文字添加底色。
C#
//创建Document实例并加载示例文档
Document document = new Document();
document.LoadFromFile("Sample.docx");
//获取第一个段落并为其设置底色
Paragraph paragaph = document.Sections[0].Paragraphs[0];
paragaph.Format.BackColor = Color.YellowGreen;
//为第三段里查找的特定文字添加底色
paragaph = document.Sections[0].Paragraphs[2];
TextSelection selection = paragaph.Find("Spire.Doc for .NET", false, true);
TextRange range = selection.GetAsOneRange();
range.CharacterFormat.TextBackgroundColor = Color.Yellow;
//保存文档
document.SaveToFile("Result.docx", FileFormat.Docx);
VB.NET
'创建Document实例并加载示例文档 Dim document As Document = New Document document.LoadFromFile("Sample.docx") '获取第一个段落并为其设置底色
Dim paragaph As Paragraph = document.Sections(0).Paragraphs(0)
paragaph.Format.BackColor = Color.YellowGreen
'为第三段里查找的特定文字添加底色 paragaph = document.Sections(0).Paragraphs(2) Dim selection As TextSelection = paragaph.Find("Spire.Doc for .NET",false,true) Dim range As TextRange = selection.GetAsOneRange range.CharacterFormat.TextBackgroundColor = Color.Yellow '保存文档
document.SaveToFile("Result.docx", FileFormat.Docx)
效果图: