10

I have a paragraph of text which I would like to appear in the center of the document. How can I do this in docx4j? I am currently using:

    PPr paragraphProperties = factory.createPPr();

    //creating the alignment
    TextAlignment align = new TextAlignment();
    align.setVal("center");
    paragraphProperties.setTextAlignment(align);

    //centering the paragraph
    paragraph.setPPr(paragraphProperties);

but it isn't working.

Nick
  • 1,743
  • 6
  • 23
  • 38

1 Answers1

16

You're almost there. Rather than setting this with a TextAlignment object, use a Jc instance (justification) instead:

PPr paragraphProperties = factory.createPPr();
Jc justification = factory.createJc();
justification.setVal(JcEnumeration.CENTER);
paragraphProperties.setJc(justification);

A simple way of figuring this stuff out:

  • Create the document (and formatting) you're looking for in Microsoft Word & save the file
  • Change the .docx file suffix to 'zip'
  • Open the zip archive, open the 'word' directory and extract the document.xml file therein
  • Examine the XML, which will give you clues as to what OpenXML objects to use
Ben
  • 7,548
  • 31
  • 45