Practical javadocx

Working with templates

Introduction

Making a document from scratch is a complex task when, for example, you search for a very elaborate visual detail of the file or to customize its content.

To simplify the document creation process, javadocx allows to use templates. In javadocx a template is a DOCX file, which contains one or multiple variables to replace for content; e.g. a text, an image, HTML, or a graphic chart.

To work with templates you have to use the class CreateDocxFromTemplate, which provides all necessary methods to modify documents.

Template methods replace placeholders in the main document body. To replace placeholders in other scopes such as header, footer, comment or footnote, the target option is available.

As an example, let's create a document with a single variable and replace it with a text.

Setting up the template

By default, javadocx uses the symbol "$" to wrap the variables to be replaced. Therefore, to define a variable with the name SIGN, add it to the document by writing $SIGN$. This way, you can define as much variables as needed, either in the content of the text, headers, footers, or in individual paragraphs, inside table forms, lists, or any other content inside the document.

If you prefer to work with another symbol, call the method setTemplateSymbol. For example, to use ‘#’ as symbol for templates, apply the code:

Instead of using just one symbol, '${ }' can also be used to wrap placeholders:

How to work with templates

The complete code to create the document using a template is the following:

CreateDocxFromTemplate inherits CreateDocx to provide all necessary methods to work with templates.

For this example, let's replace the variable SIGN for the text 'javadocx'. Type this code to do it:

You have to create a HashMap with the names of the placeholders you want to replace. Assign the new text to it, then, replace it with the method replaceVariableByText, and assign to it the HashMap previously created.

Finally, create the new document with the file name ‘tutorial_3’ using the method createDocx. The original template is not modified at any time, remaining intact for future needs.

Available methods for content replacement

The class CreateDocxFromTemplate provides multiple methods. They will be reviewed in detail later.

These methods allow to work with templates to modify, replace and delete the added variables.

When adding strings with the same name than placeholders in the same paragraph is better to use ${} to wrap placeholders.

Some of the most common methods are the following:

DOCXPath eases low level work with documents, in order to insert, move, replace, clone and delete contents.

Next - WordFragments and WordML