Search code examples
c#ms-wordopenxmlopenxml-sdk

How to align center a paragraph using open xml c#


I am trying to align to center a paragraph but is not having any affection on the paragraph.I am using OpenXml. Below is the code:

//paragraph properties 
ParagraphProperties User_heading_pPr = new ParagraphProperties();

//trying to align center a paragraph
Justification justification1 = new Justification() { Val = JustificationValues.Center };

// build paragraph piece by piece
Text text = new Text(DateTime.Now.ToString() + " , ");
Text text1 = new Text(gjenerimi + " , ");
Text text2 = new Text(merreshifren());
var run = new Run();
run.Append(text,text1,text2);
Paragraph newParagraph = new Paragraph(run);
User_heading_pPr.Append(justification1);
newParagraph.Append(User_heading_pPr);

Here is how I am trying to align center the paragraph.


Solution

  • Reverse the order in which you assign text and paragraph properties:

    User_heading_pPr.Append(justification1);
    Paragraph newParagraph = new Paragraph(User_heading_pPr);
    newParagraph.Append(run);
    

    In valid and well-formed Word Open XML the paragraph properties must precede the run. So you have to build the Open XML document the same way.

    This is a bit different than object models, the way we're typically used to dealing with them - the order does matter!