highlighting text in Docx using c#

2019-02-20 07:00发布

问题:

I need to highlight a sentence in docx file, I have this code, and its working fine for many documents , but i noticed that for some document the text inside the document is set word by word, not whole sentence, I mean each word with its own Run, so when searching for that sentence, it is not found because it is word by word in the docx. NOTE: I am working with Arabic text.

    private void HighLightText_userSentence(Paragraph paragraph, string text, string title,                           string author, decimal percentage, string _color)
{
    string textOfRun = string.Empty;
    var runCollection = paragraph.Descendants<Run>();
    Run runAfter = null;

    //find the run part which contains the characters
    foreach (Run run in runCollection)
    {
        if (run.GetFirstChild<Text>() != null)
        {
            textOfRun = run.GetFirstChild<Text>().Text.Trim();
            if (textOfRun.Contains(text))
            {
                //remove the character from thsi run part
                run.GetFirstChild<Text>().Text = textOfRun.Replace(text, "");
                runAfter = run;
                 break;

            }
        }
    }

    // create a new run with your customization font and the character as its text
    Run HighLightRun = new Run();
    RunProperties runPro = new RunProperties();
    RunFonts runFont = new RunFonts() { Ascii = "Curlz MT", HighAnsi = "Curlz MT" };
    Bold bold = new Bold();


    DocumentFormat.OpenXml.Wordprocessing.Color color = new DocumentFormat.OpenXml.Wordprocessing.Color() { Val = _color };
   DocumentFormat.OpenXml.Wordprocessing.FontSize fontSize = new DocumentFormat.OpenXml.Wordprocessing.FontSize() { Val = "22" };
    FontSizeComplexScript fontSizeComplex = new FontSizeComplexScript() { Val = "24" };

    Text runText = new Text() { Text = text };
    //runPro.Append(runFont);
    runPro.Append(bold);
    runPro.Append(color);
    //runPro.Append(fontSize);
   // runPro.Append(fontSizeComplex);

    HighLightRun.Append(runPro);
    HighLightRun.Append(runText);
    //HighLightRun.AppendChild(new Break());
    //HighLightRun.PrependChild(new Break());




    //insert the new created run part
    paragraph.InsertBefore(HighLightRun, runAfter);
}

回答1:

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