How to: Create a new docx doc

Creating a new document is only a little bit more work than opening an existing one.

Here are the steps:

1. Create a package

WordprocessingMLPackage wmlPack = new WordprocessingMLPackage();

2. Create main document part (word/document.xml)

Part wordDocumentPart = new org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart();

3. Create main document part content (see createTestPackage for an example)
4. Add the main document part to the package

wmlPack.addTargetPart(wordDocumentPart);

5. To save your new WordprocessingML package to a file

wordMLPackage.save(new java.io.File("helloworld.docx") );

That's all there is to it.

But what if you wanted to add a new styles part? Here's how:

4.1 Create a styles part

Part stylesPart = new org.docx4j.openpackaging.parts.WordprocessingML.StyleDefinitionsPart();

4.2 Populate it with some styles (Heading 1, Normal, Title etc)

((org.docx4j.openpackaging.parts.WordprocessingML.StyleDefinitionsPart) stylesPart).unmarshalDefaultStyles();

4.3 Add the styles part to the main document part relationships

wordDocumentPart.addTargetPart(stylesPart);

See createTestPackage for a complete example.