0

I used this code snippet to set color text in MS Word file

CharacterRun r = paragraph.getCharacterRun(2).insertBefore("x");
r = r.insertBefore("y");
r.setColor(6);
r.insertBefore("z);

I want to set color to only "y" character but the result I got is all "x", "y", "z" are set red color. I am wrong somewhere ? How can I set color to only "y" character - the second CharacterRun.

Thanks in advance

thoitbk
  • 269
  • 2
  • 9
  • 21

1 Answers1

0

Better late than never I suppose: It's possible that you are setting the color for the entire containing run. What you need to do is:

  • remove the overflowing text from the current run
  • add the overflowing text in the adjacent runs
  • Color the current run

Here is an example

private void highlightSubsentence(String currentRunText, String sentence, CharacterRun currentRun, int runIndex, Paragraph p, HighlighterColor color) {
        int sentenceBeginIndex = currentRunText.indexOf(sentence, 0);
        int sentenceLength = sentence.length();
        String leftSentence = currentRunText.substring(0, sentenceBeginIndex);
        String rightSentence = currentRunText.substring(sentenceBeginIndex + sentenceLength);
        boolean leftOverflow = sentenceBeginIndex > 0;
        boolean rightOverflow = sentenceBeginIndex + sentenceLength < currentRunText.length();
        boolean isInTable = p.isInTable();
        if (rightOverflow && !isInTable && runIndex + 1 < p.numCharacterRuns()) {
            currentRun.replaceText(sentence + rightSentence, sentence);
            p.getCharacterRun(runIndex + 1).insertBefore(rightSentence);
        }
        if (leftOverflow && !isInTable && runIndex > 0) {
            currentRun.replaceText(leftSentence + sentence, sentence);
            p.getCharacterRun(runIndex - 1).insertAfter(leftSentence);
        }
        currentRun.setColor(6);
    }
Ale
  • 946
  • 4
  • 17
  • 28