1

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

KSigWyatt
  • 1,368
  • 1
  • 16
  • 33
  • Can you share the document too that is giving the issue? A test document for example that has the issue. – muasif80 Nov 30 '17 at 17:11
  • Of course. [here it can be found](https://www.dropbox.com/s/gzakxny8efttuyd/Letter.doc?dl=0) – Uli Schmidl Dec 01 '17 at 07:14
  • This document in German and not readable in my latest word software as it has also macros in it. :) – muasif80 Dec 01 '17 at 08:09
  • The code is fine, I have run it and it has replaced this text successfully in my own doc file. There seems to be some problem with your document. Your document has some macros. – muasif80 Dec 01 '17 at 08:13
  • Thanks for that. I suggested this is an issue within the document - as it works for all other replacements. I guess I'll create a complete new document and try it again. – Uli Schmidl Dec 01 '17 at 08:15

0 Answers0