Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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().

like image 577
Ole Avatar asked May 29 '13 13:05

Ole


2 Answers

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.

like image 73
Ole Avatar answered Nov 14 '22 22:11

Ole


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.

like image 30
SebastianH Avatar answered Nov 14 '22 22:11

SebastianH