Home / java templ4docx docx apache-poi / Templ4docx 2.0.0 - Text Variables

Templ4docx 2.0.0 - Text Variables

17 August 2015 on java, templ4docx, docx, and apache-poi 1 minute

The most common situation is when we want to replace simple text variable. Imagine that you have an invitation template and you want to prepare filled invitation with firstname and lastname. So the only thing you need is to find variables in the template and then replace them with the correct values. Suppose that the variables in the template are as follows: ${firstname} and ${lastname}. This pattern of variables is the default one for templ4docx and does not require to define it. However, if the variables in the template have a different form, for example: #{firstname}, you must tell to templ4docx how they look like. In this case you must define the object VariablePattern in the following way new VariablePattern("#{", "}") and then set it to Docx object:

Docx docx = new Docx("template.docx");
docx.setVariablePattern(new VariablePattern("#{", "}"));

At this point you are ready to play with template.

Docx docx = new Docx("template.docx");
docx.setVariablePattern(new VariablePattern("#{", "}"));
    
// preparing variables
Variables variables = new Variables();
variables.addTextVariable(new TextVariable("#{firstname}", "Lukasz"));
variables.addTextVariable(new TextVariable("#{lastname}", "Stypka"));
        
// fill template
docx.fillTemplate(variables);
        
// save filled .docx file
docx.save("lstypka.docx");

Text variables may be placed anywhere: in a paragraph, table cell, numbered \ bullet list … The important thing is that style of text is preserved. So if you want to create, for example bolded lastname, just create bolded variable #{lastname}.


Previous

Templ4docx - Easy way to fill docx templates

A few days ago, I had to prepare Proof-of-Concept connected with filling templates prepared in docx. I took into account two libraries: org.docx4j and apache-poi. After a short play with them, the second library appears to be more suitable in my case. In order to compare these two libraries I’ve...

Next

Templ4docx 2.0.0 - Image Variables

In the previous post, I’ve written about simple text variable. Now, I would like to spend some time on Image Variables. In the previous example, we created an invitation. Now I’m going to change a little our example, and we will create a business card. The standard card has information...