Insert Header and Footer to Word using Java

Headers and footers are sections that appear in the top/ bottom margin of a Word document. They are usually used to add additional information such as title, file name, company logo as well as page numbers to a Word document and their presence makes the document more organized. This article will introduce how to insert the header and footer that contains text, images, lines and page numbers to a Word document with a 3rd party free Java API.

1# First you need to import the jar dependency to your Java application (2 methods)

● Download the free API (Free Spire.Doc for Java) and unzip it, then add the Spire.Doc.jar file to your Java application as dependency.

● Directly add the jar dependency to maven project by adding the following configurations to the pom.xml.


2# The relevant code snippet of inserting header and footer to Word document:

import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.DocPicture;
import com.spire.doc.fields.TextRange;

public class InsertHeaderAndFooter {

public static void main(String[] args) {

//Load a Word document
Document document = new Document();

//Get the first section
Section section = document.getSections().get(0);

//Call insertHeaderAndFooter method to add header and footer to the section

//Save to file
document.saveToFile("out/HeaderAndFooter.docx", FileFormat.Docx);

private static void insertHeaderAndFooter(Section section) {

//Get header and footer from a section
HeaderFooter header = section.getHeadersFooters().getHeader();
HeaderFooter footer = section.getHeadersFooters().getFooter();

//Add a paragraph to header
Paragraph headerParagraph = header.addParagraph();

//Insert a picture to header paragraph and set its position
DocPicture headerPicture = headerParagraph.appendPicture("C:\\Users\\Administrator\\Desktop\\mars.jpg");

//Add text to header paragraph
TextRange text = headerParagraph.appendText("Introduction of Mars");

//Set text wrapping to behind

//Set the bottom border style of the header paragraph

//Add a paragraph to footer
Paragraph footerParagraph = footer.addParagraph();

//Add Field_Page and Field_Num_Pages fields to the footer paragraph
footerParagraph.appendField("page number", FieldType.Field_Page);
footerParagraph.appendText(" of ");
footerParagraph.appendField("number of pages", FieldType.Field_Num_Pages);

//Set the top border style of the footer paragraph

3# A screenshot of the generated Word document:

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store