My previous post introduced how to add text and image header footer to Word document by using Free Spire.Doc for Java. This article will show you how to use this free Java library to add different headers/footers for odd and even pages in Word document.
Import the jar dependency (2 methods)
● Download the 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.
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc.free</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>
Sample Code
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.*;
import java.awt.*;
public class oddAndEvenHeaderFooter {
public static void main(String[] args) throws Exception {
String input = "sample0.docx";
String output = "out/oddAndEvenHeaderFooter.docx";
//load the document
Document doc = new Document();
doc.loadFromFile(input);
//get the first section
Section section = doc.getSections().get(0);
//set the DifferentOddAndEvenPagesHeaderFooter property as true
section.getPageSetup().setDifferentOddAndEvenPagesHeaderFooter(true);
//Add header for odd pages
Paragraph P3 = section.getHeadersFooters().getOddHeader().addParagraph();
TextRange OH = P3.appendText("Odd Page Header");
P3.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
OH.getCharacterFormat().setFontName("Arial");
OH.getCharacterFormat().setFontSize(14);
OH.getCharacterFormat().setTextColor(Color.BLUE);
//Add header for even pages
Paragraph P4 = section.getHeadersFooters().getEvenHeader().addParagraph();
TextRange EH = P4.appendText("Even Page Header");
P4.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
EH.getCharacterFormat().setFontName("Arial");
EH.getCharacterFormat().setFontSize(14);
EH.getCharacterFormat().setTextColor(Color.RED);
//Add footer for odd pages
Paragraph P2 = section.getHeadersFooters().getOddFooter().addParagraph();
TextRange OF = P2.appendText("Odd Page Footer");
P2.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
OF.getCharacterFormat().setFontName("Arial");
OF.getCharacterFormat().setFontSize(14);
OF.getCharacterFormat().setTextColor(Color.BLUE);
//Add footer for even pages
Paragraph P1 = section.getHeadersFooters().getEvenFooter().addParagraph();
TextRange EF = P1.appendText("Even Page Footer");
EF.getCharacterFormat().setFontName("Arial");
EF.getCharacterFormat().setFontSize(14);
P1.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
EF.getCharacterFormat().setTextColor(Color.RED);
//save the document
doc.saveToFile(output, FileFormat.Docx);
}
}
Top comments (0)