Martin Dames
Martin Dames

Reputation: 264

docx4j does not replace variables

I just followed approach No 2 in the VariableReplace example from docx4j 2.8.1 and everything it does, is to remove the variable markers ${}.

The steps I did:

I'd expect 'TEST' solely, and get just 'variable' without the markers in the output document.

Upvotes: 10

Views: 7338

Answers (3)

Orkhan Hasanli
Orkhan Hasanli

Reputation: 786

The main reason why variables cannot be replaced is: using plain text like ${name} instead MERGEFIELD field type. Here is the link how to add MERGEFIELD into document - https://www.systemonesoftware.com/en/support/article/38-merge-fields-in-word-for-windows

Also you can use docx-stamper with SpEL - https://github.com/thombergs/docx-stamper

Upvotes: 0

JasonPlutext
JasonPlutext

Reputation: 15863

No doubt Word is splitting your "variable" across runs, with grammar or spelling flags.

Fix it up with VariablePrepare

Put this line in after you instantiate the WordprocessingMLPackage:

VariablePrepare.prepare(wordMLPackage);

Then you can use your mappings to replace the variables.

Upvotes: 28

Ted
Ted

Reputation: 3260

I realize this is an old post, but for others that stumble onto this, another reason you can get this result is if you have incorrect "keys" in your HashMap. So in my case, I was using my old xml format as the key like

.put("<variable/>","TEST");

when I should have been using:

.put("variable","TEST");

The document itself was using tags like

${variable}

The VariableReplace code will remove the ${} formatting whether a match is found or not. So if it is not finding a match, then the keys might not match the ones in the document for some reason, and this might not strictly be related to VariablePrepare. But this was a very helpful post for me since the VariablePrepare, VariableReplace solution is now working for my purposes.

Also, I am not sure that even VariablePrepare can handle the case where you change the font, highlighting or other formatting in the middle of your tag in the document. In such cases, it will not be able to merge the tag into a single run, and so tag recognition will likely fail.

Upvotes: 2

Related Questions