Open XML: Change the text format

Within an Open XML document you may easily change the text format to create bold, italic, underline or other formatted content. The most important thing is to thin about the document structure. As explained in a previous article, the Run element should be used to group content. Elements with the same format should therefore be stored within one Run element.

The following source code shows an example how to create different text formats. The text “Hello World” is written three times to the document. Each text is placed in an own Run element with an own style, like bold, italic or strike. Of course, other styles like underline can be used in the same way.

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

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

//bold text            
run = new Run();
run.AppendChild(new RunProperties(new Bold()));
run.AppendChild(new Text("Hello world"));

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

//italic text
run = new Run();
run.AppendChild(new RunProperties(new Italic()));
run.AppendChild(new Text("Hello world"));

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

//strike
run = new Run();
run.AppendChild(new RunProperties(new Strike()));
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