Table data do not maintain font formatting of original text

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)

@hemant_thote In you code you are putting the text as new Run node, so the default formatting is applied to the Run.

cell.getFirstParagraph().getRuns().clear();
cell.getFirstParagraph().getRuns().add(new Run(cell.getDocument(), dataTypeHandler.convert(matchToken)));

Please try modifying the code like this:

for (Run r : cell.getFirstParagraph().getRuns()) {
    r.setText("");
}
cell.getFirstParagraph().getRuns().get(0).setText(dataTypeHandler.convert(matchToken));

Also, as I can see the goal of your code is to fill the table with data. Have you considered using Mail Merge With Regions or LINQ Reporting Engine.

Thanks. Solution works. We have decided to not use mail merge or linq reporting

1 Like