Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center text in docx4j

Tags:

openxml

docx4j

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.

like image 573
Nick Avatar asked Jun 17 '14 23:06

Nick


1 Answers

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
like image 78
Ben Avatar answered Oct 20 '22 23:10

Ben