How to change the background color (Highlight) of text using openxml

26 Views Asked by At

I have a bunch of .docx word templates that have specific tags in them for places we need to replace text but they also have text background color so those places are easily found and can be double checked. After they have been reviewed, I want to run them again and remove all the background colors.

Here is how i am searching and replacing text but i need to change the background color of those same search results. Its ok if i have to loop though the whole doc and change all the text background. I basically want everything to be white

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

There are 1 best solutions below

0
Kevbo On

I figured it out on my own. I ended up just looping through all the runs and change the background color (highlight). I also changed all the text to black.

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