highlighting text in Docx using c#

痴心易碎 提交于 2019-12-01 13:14:41

I recently used docX and was facing problems with searching and higlighting text. I tried an indirect way. It simple and works in most situations. I do it using the replace statement. here search text is the text you want to highlight

    using (DocX doc = DocX.Load("d:\\Sample.docx"))
       {     
           for (int i = 0; i < doc.Paragraphs.Count; i++)
           {                      
                foreach (var item in doc.Paragraphs[i])
                {
                    if (doc.Paragraphs[i] is Paragraph)
                    {
                        Paragraph sen = doc.Paragraphs[i] as Paragraph;
                        Formatting form = new Formatting();
                        form.Highlight = Highlight.yellow;
                        form.Bold = true;
                        sen.ReplaceText(searchText, searchText, false,
                     System.Text.RegularExpressions.RegexOptions.IgnoreCase,
                        form, null, MatchFormattingOptions.ExactMatch);
                    }
                }
           }
        doc.Save();
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!