docx4j
docx4j copied to clipboard
using VariablePrepare.prepare won't prepare all variables correctly
Hi, I have an issue with replacing variables in docx file. The file contains a lot of variables and is formatted. Most of them are replaced correctly but some aren't. Here's code example:
public byte [] replaceVariables(Map<String, String> placeholderMap, byte[] bytes) throws Exception {
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new ByteArrayInputStream(bytes));
VariablePrepare.prepare(wordMLPackage);
MainDocumentPart mainDocumentPart = wordMLPackage.getMainDocumentPart();
mainDocumentPart.variableReplace(placeholderMap);
ByteArrayOutputStream baos= new ByteArrayOutputStream();
wordMLPackage.save(baos);
return baos.toByteArray();
}
<w:p w14:paraId="2EFE45B1" w14:textId="42A5B701" w:rsidR="008355AE" w:rsidRDefault="00B46D75" w:rsidP="00952A23">
<w:pPr>
<w:pStyle w:val="Header3"/>
<w:spacing w:after="19"/>
<w:ind w:left="10" w:right="709"/>
</w:pPr>
<w:r>
<w:t xml:space="preserve">FIRST NAME </w:t>
</w:r>
<w:r w:rsidR="005D53E9" w:rsidRPr="00637C75">
<w:rPr>
<w:color w:val="FF0000"/>
<w:sz w:val="20"/>
<w:szCs w:val="20"/>
</w:rPr>
<w:t>${</w:t>
</w:r>
<w:proofErr w:type="spellStart"/>
<w:r w:rsidR="005D53E9" w:rsidRPr="00637C75">
<w:rPr>
<w:color w:val="FF0000"/>
<w:sz w:val="20"/>
<w:szCs w:val="20"/>
</w:rPr>
<w:t>first_</w:t>
</w:r>
<w:r w:rsidR="005D53E9" w:rsidRPr="00637C75">
<w:rPr>
<w:color w:val="FF0000"/>
</w:rPr>
<w:t>name</w:t>
</w:r>
<w:proofErr w:type="spellEnd"/>
<w:r w:rsidR="005D53E9" w:rsidRPr="00637C75">
<w:rPr>
<w:color w:val="FF0000"/>
</w:rPr>
<w:t>}</w:t>
</w:r>
</w:p>
In logs i got: org.docx4j.XmlUtils: Invalid key 'first</w:t></w:r><w:r><w:rPr><w:color w:val="FF0000"/></w:rPr><w:t>name' or key not mapped to a value
Example of placeholder which is replaced by variable correctly: ${last_name} Example result: Smith Example of placeholder which is not replaced by variable correctly: FIRST NAME ${first_name} Example result: first_name
When i manually clear formatting on the placeholder field in docx file it works correctly, but is there any other way for preparing all variables correctly?