如何使用openxml更改文本的背景颜色(突出显示)

问题描述 投票:0回答:1

我有一堆 .docx Word 模板,其中对于我们需要替换文本的位置有特定的标签,但它们也有文本背景颜色,因此这些位置很容易找到并且可以进行双重检查。审核完毕后,我想再次运行它们并删除所有背景颜色。

这是我搜索和替换文本的方式,但我需要更改相同搜索结果的背景颜色。如果我必须循环整个文档并更改所有文本背景,那就可以了。我基本上希望一切都是白色的

 var filename = Path.Combine(Properties.Settings.Default.DocPath, file);
     using (MemoryStream ms = new MemoryStream())
     {
        var bytes = File.ReadAllBytes(filename);
        ms.Write(bytes, 0, bytes.Length);
        using (WordprocessingDocument pDoc = WordprocessingDocument.Open(ms, true))
        {
           TextReplacer.SearchAndReplace(pDoc, "<<FULL_NAME>>", textInfo.ToTitleCase(FULL_NAME), true);

           TextReplacer.SearchAndReplace(pDoc, "<<FIRST>>", FIRST, true);
           TextReplacer.SearchAndReplace(pDoc, "<<MIDDLE>>", MIDDLE, true);
           TextReplacer.SearchAndReplace(pDoc, "<<LAST>>", LAST, true);

           TextReplacer.SearchAndReplace(pDoc, "<<CITY>>", textInfo.ToTitleCase(info.City), true);
           TextReplacer.SearchAndReplace(pDoc, "<<ZIP>>", textInfo.ToTitleCase(info.Zip), true);
           TextReplacer.SearchAndReplace(pDoc, "<<COUNTY>>", textInfo.ToTitleCase(info.County), true);
           TextReplacer.SearchAndReplace(pDoc, "<<STATE>>", textInfo.ToTitleCase(info.State), true);
        }
     }
  
c# openxml
1个回答
0
投票

我自己想出来了。我最终只是循环遍历所有运行并更改背景颜色(突出显示)。我还将所有文本更改为黑色。

var body = pDoc.MainDocumentPart.Document.Body;
var pars = body.Elements();
foreach (var para in pars)
{
   foreach (var run in para.Elements<Run>())
   {
      run.RunProperties.Highlight = new Highlight() { Val = HighlightColorValues.White };
      run.RunProperties.Color = new DocumentFormat.OpenXml.Wordprocessing.Color() { Val = "000000" };
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.