Open XML: Set text color

To change the foreground color of a text in an Open XML document, you have to create a Color element and add it to the run properties. The following source code shows an example application. At first a color element will be created and the value is set to a color code which represents a light green. Afterwards this color element will be added to the run properties. And of course this properties element must be assigned 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";

//text color
runProperties = new RunProperties();

var textColor = new Color();
textColor.Val = "00FF00";

runProperties.Append(textColor);

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