Practical javadocx

Headers and footers


You can add headers and footers with text, images, tables and almost any kind of content, to new documents and templates

Thanks to the WordFragment class you can easily add headers and footers, either simple ones or with multiple contents.

To make the header and footer insertion simpler, you can also use an extra template or templates from which you can import its headers and/or footers.

How to set the area of insertion of WordFragment

When creating a WordFragment object you can set where to add the contents.

By default, when creating a document with:

...simply add the content to the document. But, in the second parameter of the constructor you can define other targets:

  • "defaultHeader" or "defaultFooter": For all headers and footers
  • "firstHeader" or "firstFooter": Just for the first page
  • "evenHeader" or "evenFooter": For even number pages

For example, to add a text as the header of all pages, call the code:


The available method for adding headers is addHeader:

You need to use a WordFragment to add the content.

For example, to add an image as a header, first create the WordFragment:

Finally, insert the content in the header:


Inserting footers is like the headers process, but using addFooter:

It counts with the same options as addHeader.

This way, to add the image in the footer, use the code:


The addPageNumber method:

...allows to add pagination in headers and footers.

The available options are:

  • "type": numerical, alphabetical or page-of
  • "options": For text properties, such as size, color and alignment

For example, for adding a footer with numerical pagination, apply this method after creating the WordFragment:

Contents positioning

It's recommended to define a table to correctly organize the content of headers and footers. For example, to insert a logotype as an image, a text and a paginator after creating a WordFragment, generate the table as a new WordFragment:

And add this table to the header or footer as a new element:

Replacing headers and footers in templates

It is possible to replace the defined placeholders in the template headers and footers. To do so, you can use the methods replaceVariableByText, replaceVariableByWordFragment and other template methods.

It is mandatory to specify the target correct target, depending on where the placeholder is located.

Tips and Tricks

If the header or footer is created in MS Word, you can import it to the document with importHeadersAndFooters:

You have to indicate the path to the document to import, choosing:

  • "headerAndFooter": For importing both contents
  • "header": For importing just the headers
  • "footer": For importing just the footers

For example, to import and add both headers and footers of the DOCX, use:

Next - Pictures and images