Dogrammer
Dogrammer

Reputation: 35

Docx4j variableReplace with styling

I want to creating new Word document from a model document (.docx) and replace some text with styling.

How can I style the firstName in Bold and message as yellow highlight color?

My Code is below:

WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(templateInputStream);

MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();

VariablePrepare.prepare(wordMLPackage);

HashMap<String, String> variables = new HashMap<>();
variables.put("firstName", "fileName123");
variables.put("lastName", "lastName345");
variables.put("message", "messsssssss");

documentPart.variableReplace(variables);

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

wordMLPackage.save(outputStream);

return outputStream.toByteArray();

A screenshot of my starting model [sic: template] docx is shown below:

screenshot

A screenshot of my expected result is the following:

enter image description here

Upvotes: 2

Views: 957

Answers (1)

JasonPlutext
JasonPlutext

Reputation: 15878

Apply your desired run formatting in the source document, taking care not to "split" the run. So, for example:

        <w:r>
            <w:rPr>
                <w:b/>
                <w:bCs/>
            </w:rPr>
            <w:t>${firstName}</w:t>
        </w:r>

If Word is splitting your runs, turn off grammar and spelling correction.

If necessary, unzip the source document and check/edit in a text editor.

Upvotes: 0

Related Questions