Introduction

In this tutorial I will show you how to create Header and Footer in Word document using Apache POI API. Apache POI library is Java based API that makes our life easier to manipulate date on Microsoft office Documents. I will show you example on using both maven and gradle build tool. We will create here a Java application to create header and footer in word document using apache poi library.

A page header is text that appears in the top margin area of each page, separated from the main body of text, and usually conveying context information, such as the document title, author, creation date, or the page number. A page footer is analogous in every way to a page header except that it appears at the bottom of a page.

Prerequisites

Eclipse 4.12, JDK 1.8 or 12, Apache POI 3.15 or 4.1.1, Maven 3.6.1 or Gradle 5.6

Create Project

You basically need to create a maven or gradle based project in eclipse. The name of the project is word-header-footer-apache-poi. If you are creating maven based project then you can use the project’s name as Artifact Id and Group Id as com.roytuts.

Once the project is created and eclipse finishes build then you need to modify the pom.xml file as shown below.

Here we will add apache poi API as a dependency for working with microsoft word document or even you can work with open source word document.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.roytuts</groupId>
	<artifactId>word-header-footer-apache-poi</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>
	
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<java.version>12</java.version>
		<poi.version>4.1.1</poi.version>
	</properties>
	
	<dependencies>
		<!-- apache poi for xlsx, docx etc reading/writing -->
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
			<version>${poi.version}</version>
		</dependency>
	</dependencies>
	
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.8.1</version>
				<configuration>
					<source>${java.version}</source>
					<target>${java.version}</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

If you want to use gradle build script to create your project then use below build script to setup the project. Here also we have used the same apache poi version as you have seen in the above maven based pom.xml file.

plugins {
    id 'java-library'
}

sourceCompatibility = 12
targetCompatibility = 12

repositories {
    jcenter()
}

dependencies {
    implementation 'org.apache.poi:poi-ooxml:4.1.1'
}

We know how to create header and footer in word document manually from an option given in the word document but here we will see how to create header and footer in word document using apache poi in Java program.

Related Posts:

Java Class

Create below class to create Header and Footer text in word file.

In the below source code we create object of XPFWDocument type and we create two paragraphs with sample text.

We set indent for the paragraph and also align text for the paragraph with adjustment. We wrap the paragraph’s text.

Finally inside the try catch block we create header and footer with sample texts. I have attached an image how the final word document looks like later in the final output.

package com.roytuts.word.header.footer.apache.poi;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText;

public class WordDocxHeaderFooter {

	public static void main(String[] args) {
		wordHeaderFooter("word_docx_header_footer.docx");
	}

	public static void wordHeaderFooter(final String wordFileName) {
		XWPFDocument doc = new XWPFDocument();

		// create a paragraph with justify alignment
		XWPFParagraph p1 = doc.createParagraph();

		// first line indentation in the paragraph
		p1.setFirstLineIndent(400);

		// justify alignment
		p1.setAlignment(ParagraphAlignment.DISTRIBUTE);

		// wrap words
		p1.setWordWrapped(true);

		// XWPFRun object defines a region of text with a common set of
		// properties
		XWPFRun r1 = p1.createRun();
		String t1 = "Paragraph 1. Sample Paragraph Post. This is a sample Paragraph post. Sample Paragraph text is being cut and pasted again and again. This is a sample Paragraph post. peru-duellmans-poison-dart-frog."
				+ " Sample Paragraph Post. This is a sample Paragraph post. Sample Paragraph text is being cut and pasted again and again. This is a sample Paragraph post. peru-duellmans-poison-dart-frog.";
		r1.setText(t1);

		// create a paragraph with left alignment
		XWPFParagraph p2 = doc.createParagraph();

		// first line indentation in the paragraph
		p2.setFirstLineIndent(400);

		// left alignment
		p2.setAlignment(ParagraphAlignment.LEFT);

		// wrap words
		p2.setWordWrapped(true);

		// XWPFRun object defines a region of text with a common set of
		// properties
		XWPFRun r2 = p2.createRun();
		String t2 = "Paragraph 2. Sample Paragraph Post. This is a sample Paragraph post. Sample Paragraph text is being cut and pasted again and again. This is a sample Paragraph post. peru-duellmans-poison-dart-frog."
				+ " Sample Paragraph Post. This is a sample Paragraph post. Sample Paragraph text is being cut and pasted again and again. This is a sample Paragraph post. peru-duellmans-poison-dart-frog.";
		r2.setText(t2);

		XWPFParagraph[] pars;

		try {
			CTP ctP = CTP.Factory.newInstance();

			// header text
			CTText t = ctP.addNewR().addNewT();
			t.setStringValue("Sample Header Text");

			pars = new XWPFParagraph[1];
			p1 = new XWPFParagraph(ctP, doc);
			pars[0] = p1;

			XWPFHeaderFooterPolicy hfPolicy = doc.createHeaderFooterPolicy();
			hfPolicy.createHeader(XWPFHeaderFooterPolicy.DEFAULT, pars);

			ctP = CTP.Factory.newInstance();
			t = ctP.addNewR().addNewT();

			// footer text
			t.setStringValue("Sample Footer Text");

			pars[0] = new XWPFParagraph(ctP, doc);
			hfPolicy.createFooter(XWPFHeaderFooterPolicy.DEFAULT, pars);

			// write to word docx
			OutputStream os = new FileOutputStream(new File(wordFileName));
			doc.write(os);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

Testing the Program

Run the above class to see the output in word_docx_header_footer.docx file. The file is created under root directory of the project.

Look at the below image which gives you the final output:

create header and footer in word document using apache poi

That’s all. Hope you have got an idea how to create header and footer in word document using apache poi.

Thanks for reading.

Tags:

Leave a Reply

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