Replacing a text using CharacterRun within apache POI HWPF

871 views Asked by At

I have a small problem regarding the String replacing within Apache POI.

private static HWPFDocument replaceText(HWPFDocument doc, String findText, String replaceText) {
    Map<String, Range> ranges = new HashMap<String, Range>();

    ranges.put("COMMENTS", doc.getCommentsRange());
    ranges.put("ENDNOTE", doc.getEndnoteRange());
    ranges.put("FOOTNOTE", doc.getFootnoteRange());
    ranges.put("HEADERSTORY", doc.getHeaderStoryRange());
    ranges.put("MAINTEXT", doc.getMainTextboxRange());
    ranges.put("OVERALL", doc.getOverallRange());
    ranges.put("DEFAULT", doc.getRange());

    for (Entry<String, Range> e : ranges.entrySet()) {
        Range r = e.getValue();

        for (int i = 0; i < r.numSections(); ++i) {
            Section s = r.getSection(i);

            for (int j = 0; j < s.numParagraphs(); j++) {
                Paragraph p = s.getParagraph(j);

                for (int k = 0; k < p.numCharacterRuns(); k++) {
                    CharacterRun run = p.getCharacterRun(k);
                    String text = run.text();

                    if (text.contains(findText)) {
                        System.out.println("OLD:" + run.text());
                        run.replaceText(findText, replaceText);
                        System.out.println("NEW:" + run.text());
                    }
                }
            }
        }
    }
    return doc;
}

This works within 99 % of all cases fine, but in one case it cuts off the characters like this: in my sysoutput it appears correct as:

OLD:CUSTOMER_ROW1
NEW:Try and Error customer

but in the created Word-document it appears only as

rror customer

For me it looks like the replace does not enlarge the size of this CharacterRun and cuts everything off (from the beginning) as the size of the printed replaced text equals the size of the text to be replaced.

FYI: in other replacing cases i even replaced a 10 character long pattern with a text containing more than 500 characters and it worked fine.

Has anyone had such a problem so far and can help me? I'm using POI 3.17

0

There are 0 answers