Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 46 additions & 18 deletions src/main/java/pl/jsolve/templ4docx/strategy/TextInsertStrategy.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,22 +11,50 @@
public class TextInsertStrategy implements InsertStrategy {

@Override
public void insert(Insert insert, Variable variable) {
if (!(insert instanceof TextInsert)) {
return;
}
if (!(variable instanceof TextVariable)) {
return;
}

TextInsert textInsert = (TextInsert) insert;
TextVariable textVariable = (TextVariable) variable;
for (XWPFRun run : textInsert.getParagraph().getRuns()) {
String text = run.getText(0);
if (StringUtils.contains(text, textInsert.getKey().getKey())) {
text = StringUtils.replace(text, textVariable.getKey(), textVariable.getValue());
run.setText(text, 0);
}
}
}
public void insert(Insert insert, Variable variable) {
if (!(insert instanceof TextInsert)) {
return;
}
if (!(variable instanceof TextVariable)) {
return;
}

TextInsert textInsert = (TextInsert) insert;
TextVariable textVariable = (TextVariable) variable;

XWPFParagraph paragraph = textInsert.getParagraph();
TextSegement found = paragraph.searchText(textInsert.getKey().getKey(), new PositionInParagraph());

if (found != null) {
if (found.getBeginRun() == found.getEndRun()) {

for (XWPFRun run : paragraph.getRuns()) {
String runText = run.getText(0);
if (StringUtils.contains(runText, textInsert.getKey().getKey())) {
runText = StringUtils.replace(runText, textVariable.getKey(), textVariable.getValue());
run.setText(runText, 0);
}
}
} else {
StringBuilder b = new StringBuilder();
for (int runPos = found.getBeginRun(); runPos <= found.getEndRun(); runPos++) {
XWPFRun run = paragraph.getRuns().get(runPos);
b.append(run.getText(run.getTextPosition()));
}
String connectedRuns = b.toString();

if (StringUtils.contains(connectedRuns, textInsert.getKey().getKey())) {
connectedRuns = StringUtils.replace(connectedRuns, textVariable.getKey(), textVariable.getValue());
XWPFRun partOne = paragraph.getRuns().get(found.getBeginRun());
partOne.setText(connectedRuns, 0);
}

for (int runPos = found.getBeginRun() + 1; runPos <= found.getEndRun(); runPos++) {
XWPFRun partNext = paragraph.getRuns().get(runPos);
partNext.setText("", 0);
}
}
}

}
}