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().
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.
I spent some hours wih this problem too. I had the the same problem as mentioned in the comment above. What worked for me was this:
After finding the right paragraph to do the insertion in document.getParagraphsIterator()
, I had to use this code
XmlCursor cur = para.getCTP().newCursor();
cur.toNextSibling();
to be able to do doc.insertNewParagraph(cur)
.
To my understanding my next fault was to try to insert several paragraphs at the position of the cursor. To make this work I had to add cursor.toNextToken();
after the insertion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With