Open XML: Set background color

You can chance the foreground color of a text by define an according Color element. Changing the background color will work in the same way, but you have to create a Shading element instead of a Color element. The Shading element will allow you to define more than just a color. You may also set additional parameters like fill patterns.

The following source code shows how to create and use a Shading element. You have to create the Shading element, add it to the RunProperties and assign them to the Run element.

RunProperties runProperties = null;
Run run = null;
Paragraph paragraph = null;
Body body = new Body();

//file name            
string folder = @"<my folder>";
string fileName = folder + @"\Test.docx";

//background color
runProperties = new RunProperties();

var shading = new Shading();
shading.Color = "auto";
shading.Fill = "00FF00";
shading.Val = ShadingPatternValues.Clear;

runProperties.Append(shading);

run = new Run();
run.Append(runProperties);
run.AppendChild(new Text("Hello world"));

paragraph = new Paragraph(run);
body.AppendChild(paragraph);

//create document
var document = new Document(body);

//create file
using (var file = WordprocessingDocument.Create(
    fileName, WordprocessingDocumentType.Document))
{
    file.AddMainDocumentPart();
    file.MainDocumentPart.Document = document;
    file.MainDocumentPart.Document.Save();
}
Werbung
Dieser Beitrag wurde unter .NET, C#, Open XML veröffentlicht. Setze ein Lesezeichen auf den Permalink.

Kommentar verfassen

Trage deine Daten unten ein oder klicke ein Icon um dich einzuloggen:

WordPress.com-Logo

Du kommentierst mit deinem WordPress.com-Konto. Abmelden /  Ändern )

Facebook-Foto

Du kommentierst mit deinem Facebook-Konto. Abmelden /  Ändern )

Verbinde mit %s