Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert a paragraph in XWPFDocument

I'm doing a search and replace on a .docx file and in some cases the replace text contains newlines. I've tried a couple of techniques for this. The first was to split the replacement text up into lines and do:

run.setText(lines[0], 0);
for(int x=1; x<lines.length; x++) {
    run.addCarriageReturn();
    run.setText(lines[x]);
}

The result all ran together on a single line.

So then I did some hunting and found this code for replacing the existing paragraph with a set of paragraphs per line:

private void replaceParagraph(XWPFParagraph p, String[] paragraphs) {
    if (p != null) {
        XWPFDocument doc = p.getDocument();
        for (int i = 0; i < paragraphs.length; i++) {
            XmlCursor cursor = p.getCTP().newCursor();
            XWPFParagraph newP = doc.insertNewParagraph(cursor);
            newP.setAlignment(p.getAlignment());
            newP.getCTP().insertNewR(0).insertNewT(0).setStringValue(paragraphs[i]);
            newP.setNumID(p.getNumID());
        }
        doc.removeBodyElement(doc.getPosOfParagraph(p));
    }
}

The problem is that insertNewParagraph returns null every time. This might be because the paragraph is inside a table cell, but I haven't isolated that as the cause. I've checked the cursor, and cursor.isStart() is true which seems to comply with the requirement from the documentation.

Add a new paragraph at position of the cursor. The cursor must be on the XmlCursor.TokenType.START tag of an subelement of the documents body. When this method is done, the cursor passed as parameter points to the XmlCursor.TokenType.END of the newly inserted paragraph.

I've double-checked that doc != null, and I can't think of any other reason this might return null. Any suggestions?

like image 960
Gary Forbis Avatar asked Dec 18 '13 20:12

Gary Forbis


1 Answers

This turned out to solve the issue.

private void createParagraphs(XWPFParagraph p, String[] paragraphs) {
    if (p != null) {
        XWPFDocument doc = p.getDocument();
        XmlCursor cursor = p.getCTP().newCursor();
        for (int i = 0; i < paragraphs.length; i++) {
            XWPFParagraph newP = doc.createParagraph();
            newP.getCTP().setPPr(p.getCTP().getPPr());
            XWPFRun newR = newP.createRun();
            newR.getCTR().setRPr(p.getRuns().get(0).getCTR().getRPr());
            newR.setText(paragraphs[i]);
            XmlCursor c2 = newP.getCTP().newCursor();
            c2.moveXml(cursor);
            c2.dispose();
        }
        cursor.removeXml(); // Removes replacement text paragraph
        cursor.dispose();
    }
}
like image 162
Gary Forbis Avatar answered Sep 28 '22 08:09

Gary Forbis