Add Headers and Footers Example

This program demonstrates adding headers and footers in a Word file.

Problem Statement

Write a Java program that adds headers and footers into a Word .docx file.

Source Code

1 import java.io.*;
2 import org.apache.poi.xwpf.usermodel.*;
3 public class WordHeaderFooterExample {
4 public static void main(String[] args) {
5 System.out.println("Eduinq Word Header Footer Example");
6 try(XWPFDocument doc=new XWPFDocument()) {
7 XWPFHeaderFooterPolicy policy=doc.createHeaderFooterPolicy();
8 XWPFHeader header=policy.createHeader(XWPFHeaderFooterPolicy.DEFAULT);
9 header.createParagraph().createRun().setText("Eduinq Header Example");
10 XWPFFooter footer=policy.createFooter(XWPFHeaderFooterPolicy.DEFAULT);
11 footer.createParagraph().createRun().setText("Eduinq Footer Example");
12 try(FileOutputStream fos=new FileOutputStream("headerfooter.docx")) {
13 doc.write(fos);
14 System.out.println("Eduinq Header/Footer Added Successfully");
15 }
16 } catch(IOException e) {
17 System.out.println("Eduinq Exception: "+e.getMessage());
18 }
19 }
20 }

Program Output

					Eduinq Word Header Footer Example
Eduinq Header/Footer Added Successfully
				

Explanation

Uses XWPFHeaderFooterPolicy to create headers and footers. - Adds text runs into header/footer sections. - Exception handling ensures safe operations. - In enterprise systems, headers/footers are used for branding and pagination. Conclusion: Shows adding headers and footers in Word files.

Quick Links to Explore