Change font color in OpenXML word document (C#)

Well, I kind of brute forced my way to the answer, but it works.

List<RunProperties> runProps = element.Descendants<RunProperties>().ToList();
foreach (RunProperties rp in runProps)
{
    rp.Color = new DocumentFormat.OpenXml.Wordprocessing.Color() { Val = "0EBFE9" };
}

If anyone has a more elegant solution please add it and I'll upvote it.


I have run into similar issues and discovered that for some reason the order that you append objects to the RunProperties object actually impacts whether or not the formatting update works (The pattern I have noticed is if you append the text prior to doing your formatting, the formatting for that text does not stick).

e.g. this works (the text becomes bold, Cambria Headings, and the color is set to blue)

Run formattedRun = new Run();
RunProperties runPro = new RunProperties();
RunFonts runFont = new RunFonts() { Ascii = "Cambria(Headings)", HighAnsi = "Cambria(Headings)" };
Bold bold = new Bold();
Text text = new Text("TESTING");
Color color = new Color() { Val = "365F91", ThemeColor = ThemeColorValues.Accent1, ThemeShade = "BF" };
runPro.Append(runFont);
runPro.Append(bold);
runPro.Append(color);
runPro.Append(text);
formattedRun.Append(runPro);

but this does not (The text becomes Cambria Headings and Bold, but the color stays the standard black)

Run formattedRun = new Run();
RunProperties runPro = new RunProperties();
RunFonts runFont = new RunFonts() { Ascii = "Cambria(Headings)", HighAnsi = "Cambria(Headings)" };
Text text = new Text("TESTING");
Bold bold = new Bold();
Color color = new Color() { Val = "365F91", ThemeColor = ThemeColorValues.Accent1, ThemeShade = "BF" };
runPro.Append(runFont);
runPro.Append(bold);
runPro.Append(text);
runPro.Append(color);
formattedRun.Append(runPro);

Tags:

C#

Openxml