DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Alexis
Alexis

Posted on

Java-How to Add or Remove Header and Footer in Word documents

Word header and footer are used to format the documents or show useful information such as the topic, page number, copywrite of the documents. With Spire.Doc for Java, you can add, insert, delete or remove header and footer in Word documents in your Java applications. In this article, you will learn how to add or remove headers and footers in Word documents from the following two parts:

Getting Spire.Doc.Jar

Method 1: If you are using maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>5.4.10</version>
    </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

Method 2: If you are not using maven, you can download the JAR file from this link, extract the zip file and then import the Spire.Doc.jar file under the lib folder into your project as a dependency.

Add header and footer to Word document

Spire.Doc supports to add text, images, lines and page numbers to the header or footer of a Word documents.

  • Create a Document instance and load a sample Word document using Document.loadFromFile() method.
  • Get the first section using Document.getSections().get() method.
  • Using section.getHeadersFooters().getHeader() method to get header and section.getHeadersFooters().getFooter() method to get footer.
  • Add a paragraph to header using header.addParagraph() method.
  • Insert an image as a header using headerParagraph.appendPicture() method and set the position for the image.
  • Insert text as a header using headerParagraph.appendText() method and set the text format.
  • Add a paragraph to footer using footer.addParagraph() method.
  • Add Field_Page field and Field_Num_Pages field to the footer paragraph using footerParagraph.appendField() method and set the format for them.
  • Save the document to another file using Document.saveToFile() method.
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.DocPicture;
import com.spire.doc.fields.TextRange;


public class insertHeaderFooter {
    public static void main(String[] args) throws Exception {

        //Create a Document instance
        Document document = new Document();

        //Load a sample Word document
        document.loadFromFile("Sample.docx");
        //Get the first section
        Section section = document.getSections().get(0);

        //Call insertHeaderAndFooter method to add header and footer to the section
        insertHeaderAndFooter(section);

        //Save the document to another file
        document.saveToFile("output/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("Logo.png");
        headerPicture.setHorizontalAlignment(ShapeHorizontalAlignment.Left);
        headerPicture.setVerticalOrigin(VerticalOrigin.Top_Margin_Area);
        headerPicture.setVerticalAlignment(ShapeVerticalAlignment.Bottom);

        //Add text to header paragraph
        TextRange text = headerParagraph.appendText("Demo of Spire.Doc");
        text.getCharacterFormat().setFontName("Arial");
        text.getCharacterFormat().setFontSize(10);
        text.getCharacterFormat().setItalic(true);
        headerParagraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Right);

        //Set text wrapping style
        headerPicture.setTextWrappingStyle(TextWrappingStyle.Behind);

        //Set the bottom border style of the header paragraph
        headerParagraph.getFormat().getBorders().getBottom().setBorderType(BorderStyle.Single);
        headerParagraph.getFormat().getBorders().getBottom().setLineWidth(1f);

        //Adjust the header distance
        section.getPageSetup().setHeaderDistance(100);

        //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);
        footerParagraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);

        //Set the top border style of the footer paragraph
        footerParagraph.getFormat().getBorders().getTop().setBorderType(BorderStyle.Single);
        footerParagraph.getFormat().getBorders().getTop().setLineWidth(1f);

        //Adjust the footer distance
        section.getPageSetup().setFooterDistance(70);
    }
}

Enter fullscreen mode Exit fullscreen mode

Insert header and footer

Remove header and footer from Word document

There are three kinds of headers and footers in a Word documents, on first page, on odd pages and on even pages. This sample demonstrates how to remove all the headers and footers on first page, on odd pages and on even pages in a Word document using Spire.Doc for Java.

  • Create a Document instance.
  • Load a sample Word document using Document.loadFromFile() method.
  • Get the first section using Document.getSections().get() method.
  • Get all the headers and footers by section.getHeadersFooters().getByHeaderFooterType() method.
  • Remove all the headers and footers using HeaderFooter.getChildObjects().clear() method.
  • Save the document to another file using Document.saveToFile() method.
import com.spire.doc.*;
import com.spire.doc.documents.*;

public class removeHeaderFooter {
    public static void main(String[] args) throws Exception {

        //Create a Document instance
        Document document = new Document();

        //Load a sample Word document
        document.loadFromFile("Test.docx");

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

        //Remove the header on the first page
        HeaderFooter header = section.getHeadersFooters().getByHeaderFooterType(HeaderFooterType.Header_First_Page);
        if (header != null)
            header.getChildObjects().clear();

        //Remove the header on the odd pages
        header = section.getHeadersFooters().getByHeaderFooterType(HeaderFooterType.Header_Odd);
        if (header != null)
            header.getChildObjects().clear();

        //Remove the header on the even pages
        header = section.getHeadersFooters().getByHeaderFooterType(HeaderFooterType.Header_Even);
        if (header != null)
            header.getChildObjects().clear();


        //Remove footer on the first page
        HeaderFooter footer = section.getHeadersFooters().getByHeaderFooterType(HeaderFooterType.Footer_First_Page);
        if (footer != null)
            footer.getChildObjects().clear();

        //Remove footer on the odd pages
        footer = section.getHeadersFooters().getByHeaderFooterType(HeaderFooterType.Footer_Odd);
        if (footer != null)
            footer.getChildObjects().clear();

        //Remove footer on the even pages
        footer = section.getHeadersFooters().getByHeaderFooterType(HeaderFooterType.Footer_Even);
        if (footer != null)
            footer.getChildObjects().clear();


        //Save the result document
        document.saveToFile("output/RemoveHeaderfooter.docx", FileFormat.Docx_2013);

    }
}
Enter fullscreen mode Exit fullscreen mode

Remove header and footer

Conclusion

In this article, you have learned how to Add, Insert, Remove or Delete Header and Footer in Word documents with the help of Spire.Doc for Java. If you have any other questions, please feel free to check the Spire.Doc forums.

Top comments (0)

Why You Need to Study Javascript Fundamentals

>> Check out this classic DEV post <<