How to create header and footer for word documents using docx4j

In this post, I have written a Java program to create header and footer for word documents using docx4j library.

Docx4j is an open source Java library for creating and manipulating Microsoft Open XML (Word docx, Powerpoint pptx, and Excel xlsx) files. It is similar to Microsoft’s OpenXML SDK, but for Java. docx4j uses JAXB to create the in-memory object representation.

Each Word document can be represented in XML format as specified by Open XML. Based on this XML representation docx4j has provided an API which can be used to create and manipulate word documents.

docx4j jar download –

Getting Started guide  – Docx4j

Java program to create header and footer for word documents using docx4j

When you run the above program, a word document named “helloworld.docx” will be created in the C drive. Here is the snapshot of the word document created.
create header and footer for word documents using docx4j

Open the word document and save it as an XML file by choosing the file type as “Word XML Document” in the save as dialog box. Now open the XML file in browser/editor and look at the structure. You will see that each element in header, footer and the paragraph will correspond to a class we used in the program to create the content. For example, below is the structure of the header text in the xml document.

Here <w:p> is mapped to the class org.docx4j.wml.P, <w:r> mapped to org.docx4j.wml.R, <w:rPr> mapped to org.docx4j.wml.RPr and <w:t> is mapped to the class org.docx4j.wml.Text.

So once you understand the XML representation, you can easily use the appropriate classes in the library to achieve the desired functionality.

The program contains enough comments to understand what the code does. Hope you find this useful. If you have any doubt, post it in the comments section.

The following two tabs change content below.
Working as a Java developer since 2010. Passionate about programming in Java. I am a part time blogger.

Add Comment

Required fields are marked *. Your email address will not be published.