Insert a line break inside a paragraph in XWPFDocument
Asked Answered
W

2

13

I am writing values into a word template using apache poi 3.8. I replace specific strings in a word file (keys) with required values, e.g. word document has a paragraph containing key %Entry1%, and I want to replace it with "Entry text line1 \nnew line". All replaced keys and values are stored in a Map in my realisation.

Map<String, String> replacedElementsMap;

The code for HWPFDocument is:

Range range = document.getRange();
for(Map.Entry<String, String> entry : replacedElementsMap.entrySet()) {
            range.replaceText(entry.getKey(), entry.getValue());
}

This code works fine, I just have to put \n in the entry string for a line break. However I can't find similiar method for XWPFDocument. My current code for XWPFDocument is:

List<XWPFParagraph> xwpfParagraphs = document.getParagraphs();
for(XWPFParagraph xwpfParagraph : xwpfParagraphs) {
            List<XWPFRun> xwpfRuns = xwpfParagraph.getRuns();
            for(XWPFRun xwpfRun : xwpfRuns) {
                String xwpfRunText = xwpfRun.getText(xwpfRun.getTextPosition());
                for(Map.Entry<String, String> entry : replacedElementsMap.entrySet()) {
                    if (xwpfRunText != null && xwpfRunText.contains(entry.getKey())) {
                        xwpfRunText = xwpfRunText.replaceAll(entry.getKey(), entry.getValue());
                    }
                }
                xwpfRun.setText(xwpfRunText, 0);
            }
        }

Now the "\n"-string doesn't result in the carriage return, and if I use xwpfRun.addCarriageReturn(); I just get a line break after the paragraph. How should I create new lines in xwpf correctly?

Wayless answered 12/2, 2013 at 10:44 Comment(2)
If you add a line break in a paragraph in Office, then look at the resulting XML, does that offer a clue as to what's needed?Kerk
XML does contain the linebreak, but I wanted a new break after each newline symbol, so in the end I had to create new paragrpahs manually.Wayless
R
29

I have another solution and it is easier:

            if (data.contains("\n")) {
                String[] lines = data.split("\n");
                run.setText(lines[0], 0); // set first line into XWPFRun
                for(int i=1;i<lines.length;i++){
                    // add break and insert new text
                    run.addBreak();
                    run.setText(lines[i]);
                }
            } else {
                run.setText(data, 0);
            }
Ricercare answered 29/7, 2014 at 6:19 Comment(2)
I used run.addCarriageReturn(); and does not work. After change to run.addBreak, according you suggest, works fine. Great, but... why?Studio
addBreak() seems to append a break at the end of the run. What if there are already some text elements in the run? Is there a possibility to add a break somewhere in between?Upwind
W
3

After all, I had to create paragraphs manually. Basically, I split the replace string to an array and create a new paragraph for each array element. Here is the code:

protected void replaceElementInParagraphs(List<XWPFParagraph> xwpfParagraphs,
                                              Map<String, String> replacedMap) {
        if (!searchInParagraphs(xwpfParagraphs, replacedMap)) {
            replaceElementInParagraphs(xwpfParagraphs, replacedMap);
        }
    }

 private boolean searchInParagraphs(List<XWPFParagraph> xwpfParagraphs, Map<String, String> replacedMap) {
        for(XWPFParagraph xwpfParagraph : xwpfParagraphs) {
            List<XWPFRun> xwpfRuns = xwpfParagraph.getRuns();
            for(XWPFRun xwpfRun : xwpfRuns) {
                String xwpfRunText = xwpfRun.getText(xwpfRun.getTextPosition());
                for(Map.Entry<String, String> entry : replacedMap.entrySet()) {
                    if (xwpfRunText != null && xwpfRunText.contains(entry.getKey())) {
                        if (entry.getValue().contains("\n")) {
                            String[] paragraphs = entry.getValue().split("\n");
                            entry.setValue("");
                            createParagraphs(xwpfParagraph, paragraphs);
                            return false;
                        }
                        xwpfRunText = xwpfRunText.replaceAll(entry.getKey(), entry.getValue());
                    }
                }
                xwpfRun.setText(xwpfRunText, 0);
            }
        }
        return true;
    }

 private void createParagraphs(XWPFParagraph xwpfParagraph, String[] paragraphs) {
        if(xwpfParagraph!=null){
            for (int i = 0; i < paragraphs.length; i++) {
                XmlCursor cursor = xwpfParagraph.getCTP().newCursor();
                XWPFParagraph newParagraph = document.insertNewParagraph(cursor);
                newParagraph.setAlignment(xwpfParagraph.getAlignment());
                newParagraph.getCTP().insertNewR(0).insertNewT(0).setStringValue(paragraphs[i]);
                newParagraph.setNumID(xwpfParagraph.getNumID());
            }
            document.removeBodyElement(document.getPosOfParagraph(xwpfParagraph));
        }
    }
Wayless answered 13/2, 2013 at 6:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.