thombergs / docx-stamper

Easy-to-use template engine for creating docx documents in Java.
MIT License
213 stars 90 forks source link

replaceWordWith doesn't work within a table cell #96

Open dallanmc opened 2 years ago

dallanmc commented 2 years ago

My goal is to replace the inline variable replacement with comments. This works well for the most part, but replaceWordWith isn't working within tables. Just in case anyone is interested in a fix, you can do the following:

    private void walkTableCell(TableCellCoordinates cellCoordinates) {
        onTableCell(cellCoordinates);
        int elementIndex = 0;
        for (Object cellContentElement : cellCoordinates.getCell().getContent()) {
            if (XmlUtils.unwrap(cellContentElement) instanceof P) {
                P p = (P) cellContentElement;
                ParagraphCoordinates paragraphCoordinates = new ParagraphCoordinates(p, elementIndex, cellCoordinates);
                onParagraph(paragraphCoordinates);     // <--- this is the line we need to replace

If you replace that last line above with a call to walkParagraph(paragraphCoordinates); then all the comments within the cell will be processed.

I've also found a (hacky, for the moment) way to get this to work with repeating rows. If the comment expression resolves to a string literal, it will just insert that into the cell. So you can insert an inline variable using this. The inline variable then gets replaced, because that process happens after the comments are processed.

So if the contents of your comment are replaceWordWith("${name}")

Then ${name} will be inserted inline into the document. It will then be replaced as normal with the value of name from the context object.