Search code examples
c#openxmlopenxml-sdkboldunderline

Cumulate RunProperties on Run with OpenXML SDK 2.0


I was wondering if I could cumulate RunProperties on Run

Run run = new Run(new Text("test"));
RunProperties runProperties = new RunProperties();
runProperties.AppendChild<Bold>(new Bold());
runProperties.AppendChild<Underline>(new Underline());
run.AppendChild<RunProperties>(runProperties);

In this case, I only got Bold text but not Underline.

Please help


Solution

  • I tried your example and indeed it only did bold for me and not underline. I worked it a bit and ended up with this:

    using (WordprocessingDocument doc = WordprocessingDocument.Open(destFileName, true))
    {
    
        Run run = new Run();
        RunProperties runProperties = new RunProperties();
    
        runProperties.AppendChild<Underline>(new Underline() { Val = DocumentFormat.OpenXml.Wordprocessing.UnderlineValues.Single });
        runProperties.AppendChild<Bold>(new Bold());
        run.AppendChild<RunProperties>(runProperties);
        run.AppendChild(new Text("test"));
    
        //Note: I had to create a paragraph element to place the run into.
        Paragraph p = new Paragraph();
        p.AppendChild(run);
        doc.MainDocumentPart.Document.Body.AppendChild(p);
    }
    

    Basically, this changed:

    new Underline() { Val = DocumentFormat.OpenXml.Wordprocessing.UnderlineValues.Single }
    

    You have to specify the type of underline you want and not just leave it up to the Underline class's constructor. I just specified Single and it worked for me.