Hi,
I am working on program to replace text in word document. I am running across issue where replaced text do not maintain the formatting of original text. I am attaching there original template file and generated pdf file along with code used.
public void processTable(Table table, List<TabelRowToken> tableRows) {
int tokeRowIndex = identifyTokenRow(table);
Row tokenRow = table.getRows().get(tokeRowIndex);
List<Row> newRows = new ArrayList<>();
for (TabelRowToken tableRow : tableRows) {
Row newRow = (Row) tokenRow.deepClone(true);
newRows.add(getNewRowWithReplacedTokens(newRow, tableRow.getTblColTokens()));
}
if(newRows != null && !newRows.isEmpty()){
for(Row newRow : newRows){
table.insertAfter(newRow, tokenRow);
}
table.getRows().remove(tokenRow);
}
}
private int identifyTokenRow(Table table){
int i = 0;
for (Row row : table.getRows()) {
for(Cell cell : row.getCells()){
String cellText = cell.getText();
if (cellText != null && cellText.contains("_Col_")) {
return i;
}
}
i++;
}
return 0;
}
private Row getNewRowWithReplacedTokens(Row row, List<Token> tokens) {
for (Cell cell : row.getCells()) {
String cellText = cell.getText();
if (cellText != null && cellText.contains("_Col_")) {
List<Token> matchTokens = tokens.stream().filter(t-> cellText.contains(t.getName().getToken())).collect(Collectors.toList());
if(matchTokens != null && !matchTokens.isEmpty()){
Token matchToken = matchTokens.get(0);
String replaceText = matchToken.getText() != null? matchToken.getText() : "";
cell.getFirstParagraph().getRuns().clear();
cell.getFirstParagraph().getRuns().add(new Run(cell.getDocument(), dataTypeHandler.convert(matchToken)));
}
}
}
return row;
}
Template File.docx (19.1 KB)
Generated file.pdf (49.2 KB)