Page 1 of 1

Numbered Headings

PostPosted: Fri Aug 19, 2011 1:18 am
by evi
Hi,

I am looking for a solution how to create headings with numbers (think it is called multilevel list in Word 2007).

What I am looking for is a way to accomplish this:

Code: Select all
1. Heading 1
1.1 Heading 2
1.1.1 Heading 3
1.1.2 Heading 3
1.2 Heading 2
2. Heading 1
2.1 Heading 2
...


Is there an easy way of doing this? Tried to look into the sample code, but couldn't find anything related.

Thanks,
erik

Re: Numbered Headings

PostPosted: Fri Aug 19, 2011 6:25 pm
by jason
For a general overview, have at look at section 2.10 (page 46) of http://www.ecma-international.org/news/ ... Primer.pdf

You need to do 2 things really:

First, make sure you have a numbering definitions part which contains the numbering you want to use. The easiest way to do this is to use Word to save a docx containing the numbering you are after. (The NumberingRestart sample shows you how to create a numbering part from scratch)

Second, make sure that your heading definition (in styles.xml) includes a reference to the number you want to use. You could do that in Word as well, but if you want to do it via docx4j, fetch the content of the styles part:

Code: Select all
Styles styles = wordMLPackage.getMainDocumentPart().getStyleDefinitionsPart().getJaxbElement()


find the style of interest (ie your heading), then add something like the following to its w:pPr:

Code: Select all
      <w:numPr>
        <w:numId w:val="1"/>
      </w:numPr>

Re: Numbered Headings

PostPosted: Fri Aug 19, 2011 9:27 pm
by evi
Hi Jason,

Thanks for your reply. I got it working based upon your input.

Since working with the style's within the code requires quite some lines of code to write; I will try another approach. E.g. create a new word document, extract the styles.xml and insert this into the generated document (somehow). This will probably make it easier to maintain the code also.

-erik

Re: Numbered Headings

PostPosted: Fri Aug 19, 2011 9:44 pm
by evi
If someone else is interested, this piece of code did the work...

Code: Select all
WordprocessingMLPackage wmlp = WordprocessingMLPackage.createPackage(PageSizePaper.A4, false);
MainDocumentPart mdp = wmlp.getMainDocumentPart();

// Add numbering part
NumberingDefinitionsPart ndp = new NumberingDefinitionsPart();
ndp.setJaxbElement((Numbering) unmarshalResource("numbering.xml"));
mdp.addTargetPart(ndp);
         
// Add styles part
StyleDefinitionsPart sdp = new StyleDefinitionsPart();
sdp.setJaxbElement((Styles) unmarshalResource("styles.xml"));
mdp.addTargetPart(sdp);


The "unmarshalResource" method is just an utility method that reads the content of a resource from the classpath into a string and then does "XmlUtils.unmarshalString(...)".

The numbering.xml and styles.xml was extracted from a DOCX file created from scratch in Word.