I found a workaround. The issue was that the placeholder was getting split and becoming part of a different run.
First, I sysout each run and found - ${ - run1, collegName - run2 , } - run 3. So, inside the Word document, I removed the placeholder "${collegeName}" and replaced it with just "collegeName". And in the service I just checked, is this word part of the run, If yes, I replaced the text. It worked, but I feel this is not the correct way to do it. I want to know how to make these 3 runs ${ - run 1, collegName - run 2, } - run 3, into a single run.
Before -
// Replace placeholders
String updatedText = fullText.toString();
for (Map.Entry<String, String> entry : data.entrySet()) {
updatedText = updatedText.replace("${" + entry.getKey() + "}", entry.getValue());
}
Now -
for (int i = 0; i < runs.size(); i++) {
XWPFRun run = runs.get(i);
String runText = run.getText(0);
if (runText != null) {
for (Map.Entry<String, String> entry : data.entrySet()) {
String placeholder = entry.getKey();
if (runText.contains(placeholder)) {
runText = runText.replace(placeholder, entry.getValue());
run.setText(runText, 0); // Replace text without affecting formatting
}
}
}
And I think answer given by @NiXiang also should work, as he is Concatenating all run texts and perform replacement.