The documentPart.getJaxbElement().getBody().getContent().add(paragraph);
way doesn't seem to work at all.
Have you tried to use documentPart.addObject(paragraph);
instead?
See full example that inserts page break between two paragraphs:
public class PageBreakExample {
private static ObjectFactory objectFactory = new ObjectFactory();
public static void main(String[] args) throws InvalidFormatException,
Docx4JException {
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();
// create new paragraph with a run containing text and add it to the document.
P paragraph1 = objectFactory.createP(); // create new paragraph
R run1 = objectFactory.createR(); // create new run
Text text1 = objectFactory.createText(); // create text
text1.setValue("This is text in paragraph 1");
run1.getContent().add(text1); // add text ton the run
paragraph1.getContent().add(run1); // add run to paragraph
wordMLPackage.getMainDocumentPart().addObject(paragraph1);
addPageBreak(wordMLPackage.getMainDocumentPart());
// proceed to create another paragraph with a run containing text.
P paragraph2 = objectFactory.createP(); // create new paragraph
R run2 = objectFactory.createR(); // create new run
Text text2 = objectFactory.createText(); // create text
text2.setValue("This is text in paragraph 2");
run2.getContent().add(text2); // add text ton the run
paragraph2.getContent().add(run2); // add run to paragraph
wordMLPackage.getMainDocumentPart().addObject(paragraph2); // add to main document part
wordMLPackage.save(new java.io.File("two_paragraphs_page_break.docx")); // save
}
private static void addPageBreak(MainDocumentPart documentPart) {
P paragraph = objectFactory.createP();
R run = objectFactory.createR();
P p = objectFactory.createP();
// Create object for r
R r = objectFactory.createR();
p.getContent().add(r);
// Create object for br
Br br = objectFactory.createBr();
r.getContent().add(br);
br.setType(org.docx4j.wml.STBrType.PAGE);
documentPart.addObject(p);
}
}