2014-09-30 47 views
1

我需要在docx文件中高亮显示一个句子,我有这段代码,它对许多文档都很好,但我注意到对于某些文档文档中的文本是逐字设置的,不是全部的句子,我的意思是每个单词都有自己的Run,所以当搜索这个句子时,找不到它,因为它在docx中是逐字的。 注意:我正在处理阿拉伯语文本。使用c高亮显示Docx中的文本#

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

回答

3

我最近使用了docX,并且遇到了搜索和高亮文本的问题。我尝试了一种间接的方式。它很简单,适用于大多数情况。我使用replace语句来完成它。 这里搜索文本是你想要突出显示的文本

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

谢谢你我会试试 – 2015-05-10 20:50:41