Java – Insert a XWPFParagraph in any position of a XWPFDocument


Do you know if is there a way to insert a paragraph (XWPFParagraph) inside a paragraph fullfilled document (XWPFDocument)?.

There is a method to "change" an already existing paragraph inside the document to another paragraph (XWPFDocument.setParagraph()) but I don't figure out how to insert NEW paragraphs into a specific position inside the document, not at the end with XWPFDocument.createParagraph().

Best Solution

I've found a solution. The XWPFDocument has an ugly method insertNewParagraph(org.apache.xmlbeans.XmlCursor cursor). As you can see this method is passed a XmlCursor from the xmlbeans library. We can then do this:

XmlCursor cursor = par.getCTP().newCursor();
XWPFParagraph new_par = doc.insertNewParagraph(cursor);
new_par.createRun().setText("Stupid text");

Par is an XWPFParagraph inside the XWPFDocument doc. The new paragraph inserted (new_par in this snippet) will be inserted BEFORE the XmlObject the XmlCursor is pointing to.

Hope this help someone.