Headers are text or pictures on the top of pages in Word documents while footers are at the bottom. People usually use headers and footers to display some important information about documents, such as copyright, author information, and page numbers or just to make the document more good-looking and professional. They can be inserted into a Word document on every page, only on the first page, or differently on odd pages and even pages. This article will show how to insert headers and footers into Word documents programmatically using Spire.Doc for Java.

Install Spire.Doc for Java

First of all, you're required to add the Spire.Doc.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use 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>14.1.3</version>
    </dependency>
</dependencies>

Insert Headers and Footers into a Word Document

To insert a header or a footer into a Word document using Spire.Doc for Java, you need to use Section.getHeadersFooters().getHeader() and Section.getHeadersFooters().getFooter() methods to get them and then add paragraphs to them to insert pictures, text, or page number fields.

The detailed steps for inserting headers and footers are as follows:

  • Create an instance of Document class.
  • Load a Word document using Document.loadFromFIle() method.
  • Get the first section using Document.getSections().get() method.
  • Call the custom method insertHeaderAndFooter() to insert a header and a footer into the section.
  • Save the document using Document.saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.TextRange;

public class insertHeaderAndFooter {

    public static void main(String[] args) {

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

        //Load a Word document
        document.loadFromFile("We Are Interwoven Beings.docx");

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

        //Call the custom method insertHeaderAndFooter() to insert headers and footers to the section
        insertHeaderAndFooter(section);

        //Save the document
        document.saveToFile("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 the header
        Paragraph headerParagraph = header.addParagraph();

        //Add text to the header paragraph
        TextRange text = headerParagraph.appendText("Philosophy\rWe Are Interwoven Beings");
        text.getCharacterFormat().setFontName("Arial");
        text.getCharacterFormat().setFontSize(12);
        text.getCharacterFormat().setItalic(true);
        headerParagraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);

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

        //Add a paragraph to the 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);
    }
}

Java: Insert Headers and Footers into Word Documents

Insert a Header and a Footer Only into the First Page of a Word Document

Sometimes we only need to insert a header and a footer into the first page, which can be realized by Spire.Doc for Java as well. We can use Section.getPageSetup().setDifferentFirstPageHeaderFooter() method to make the headers and footers of the first page different from other pages.

The detailed steps for inserting header and footer only into the first page are as follows:

  • Create a Document class instance.
  • Load a Word document using Document.loadFromFile() method.
  • Get the first section using Document.getSections().get() method.
  • Make the headers and footers of the first page different from other pages using Section.getPageSetup().setDifferentFirstPageHeaderFooter() method.
  • Call the custom method insertHeaderAndFooterFirst() to insert a header and a footer into the first page.
  • Save the document using Document.saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.DocPicture;
import com.spire.doc.fields.TextRange;

import java.awt.*;

public class insertHeaderAndFooter {

    public static void main(String[] args) {

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

        //Load a Word document
        document.loadFromFile("We Are Interwoven Beings.docx");

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

        //Make the headers and footers of the first page different from other pages
        section.getPageSetup().setDifferentFirstPageHeaderFooter(true);

        //Call the custom method insertHeaderAndFooterFirst() to insert a header and a footer into the first page
        insertHeaderAndFooterFirst(section);

        //Save the document
        document.saveToFile("FirstPageHeaderAndFooter.docx", FileFormat.Docx);
    }

    private static void insertHeaderAndFooterFirst(Section section) {

        //Get header and footer of the first page
        HeaderFooter header = section.getHeadersFooters().getFirstPageHeader();
        HeaderFooter footer = section.getHeadersFooters().getFirstPageFooter();

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

        //Add text to the header paragraph
        TextRange text = headerParagraph.appendText("Philosophy");
        text.getCharacterFormat().setFontName("Arial");
        text.getCharacterFormat().setFontSize(14);
        text.getCharacterFormat().setTextColor(Color.blue);
        text.getCharacterFormat().setItalic(true);
        headerParagraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Right);

        //Insert a picture into the header paragraph and set its position
        DocPicture headerPicture = headerParagraph.appendPicture("Header.png");
        headerPicture.setHorizontalAlignment(ShapeHorizontalAlignment.Left);
        headerPicture.setVerticalOrigin(VerticalOrigin.Top_Margin_Area);
        headerPicture.setVerticalAlignment(ShapeVerticalAlignment.Center);

        //Set text wrapping style to Behind
        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);

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

        //Add text to the footer paragraph
        TextRange text1 = footerParagraph.appendText("We Are Interwoven Beings");
        text1.getCharacterFormat().setFontName("Arial");
        text1.getCharacterFormat().setFontSize(14);
        text1.getCharacterFormat().setTextColor(Color.BLUE);
        text1.getCharacterFormat().setItalic(true);
        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);
    }
}

Java: Insert Headers and Footers into Word Documents

Insert Different Headers and Footers into Odd Pages and Even Pages

We may also encounter situations where we need to insert different headers and footers into odd pages and even pages. Spire.Doc for Java provides a method Section.getPageSetup().setDifferentOddAndEvenPagesHeaderFooter(), which can make headers and footers different on odd pages and even pages, to meet such needs.

The detailed steps for inserting different headers and footers into odd pages and even pages are as follows:

  • Create an object of Document class.
  • Load a Word document using Document.loadFromFile() method.
  • Get the first section using Document.getSections().get() method.
  • Make the headers and footers of odd pages and even pages different using Section.getPageSetup().setDifferentOddAndEvenPagesHeaderFooter() method.
  • Call the custom method insertHeaderAndFooterOddEven() to insert different headers and footers into odd pages and even pages.
  • Save the document using Document.saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.TextRange;

import java.awt.*;

public class insertHeaderAndFooter {

    public static void main(String[] args) {

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

        //Load a Word document
        document.loadFromFile("We Are Interwoven Beings.docx");

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

        //Make the headers and footers of odd pages and even pages different
        section.getPageSetup().setDifferentOddAndEvenPagesHeaderFooter(true);

        //Call the custom method insertHeaderAndFooterOddEven() to insert different headers and footers into odd pages and even pages
        insertHeaderAndFooterOddEven(section);

        //Save the document
        document.saveToFile("OddEvenHeaderAndFooter.docx", FileFormat.Docx);
    }

    private static void insertHeaderAndFooterOddEven(Section section) {

        //Insert odd header
        Paragraph P1 = section.getHeadersFooters().getOddHeader().addParagraph();
        TextRange OH = P1.appendText("Odd Header");
        P1.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
        OH.getCharacterFormat().setFontName("Arial");
        OH.getCharacterFormat().setFontSize(16);
        OH.getCharacterFormat().setTextColor(Color.RED);

        //Insert even header
        Paragraph P2 = section.getHeadersFooters().getEvenHeader().addParagraph();
        TextRange EH = P2.appendText("Even Header");
        P2.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
        EH.getCharacterFormat().setFontName("Arial");
        EH.getCharacterFormat().setFontSize(16);
        EH.getCharacterFormat().setTextColor(Color.RED);

        //Insert odd footer
        Paragraph P3 = section.getHeadersFooters().getOddFooter().addParagraph();
        TextRange OF = P3.appendText("Odd Footer");
        P3.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
        OF.getCharacterFormat().setFontName("Arial");
        OF.getCharacterFormat().setFontSize(16);
        OF.getCharacterFormat().setTextColor(Color.RED);

        //Insert even footer
        Paragraph P4 = section.getHeadersFooters().getEvenFooter().addParagraph();
        TextRange EF = P4.appendText("Even Footer");
        EF.getCharacterFormat().setFontName("Arial");
        EF.getCharacterFormat().setFontSize(16);
        P4.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
        EF.getCharacterFormat().setTextColor(Color.RED);
    }
}

Java: Insert Headers and Footers into Word Documents

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Java: Create a Table in Word

2019-05-24 09:25:50 Written by Koohji

A table is a common way to present tabular data in a Word document. It helps a lot in organizing a big set of information. In this article, you'll learn how to create how to create a table, fill the table with data, and apply formatting to the table cells using Spire.Doc for Java.

Install Spire.Doc for Java

First of all, you're required to add the Spire.Doc.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use 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>14.1.3</version>
    </dependency>
</dependencies>

Create a Simple Table in Word

The table below lists some of the core classes and methods responsible for creating as well as formatting a table.

Name Description
Table Class Represents a table in a Word document.
TableRow Class Represents a row in a table.
TableCell Class Represents a specific cell in a table.
Section.addTbale() Method Adds a new table to the specified section.
Table.resetCells() Method Resets row number and column number.
Table.getRows() Method Gets the table rows.
TableRow.setHeight() Method Sets the height of the specified row.
TableRow.getCells() Method Returns the cells collection.
TableRow.getFormat() Method Gets the format of the specified row.

The following are the steps to create a simple table in a Word document.

  • Create a Document object, and add a section to it.
  • Prepare the data for the header row and other rows, storing them in a one-dimensional string array and a two-dimensional string array respectively.
  • Add a table to the section using Section.addTable() method.
  • Insert data to the header row, and set the row formatting, including row height, background color, and text alignment.
  • Insert data to the rest of the rows, and apply formatting to these rows.
  • Save the document to another file using Document.saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.TextRange;

import java.awt.*;

public class CreateTable {

    public static void main(String[] args) {

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

        //Add a section
        Section section = document.addSection();

        //Define the data for table
        String[] header = {"Name", "Capital", "Continent", "Area", "Population"};
        String[][] data =
                {
                        new String[]{"Argentina", "Buenos Aires", "South America", "2777815", "32300003"},
                        new String[]{"Bolivia", "La Paz", "South America", "1098575", "7300000"},
                        new String[]{"Brazil", "Brasilia", "South America", "8511196", "150400000"},
                        new String[]{"Canada", "Ottawa", "North America", "9976147", "26500000"},
                        new String[]{"Chile", "Santiago", "South America", "756943", "13200000"},
                        new String[]{"Colombia", "Bogota", "South America", "1138907", "33000000"},
                        new String[]{"Cuba", "Havana", "North America", "114524", "10600000"},
                        new String[]{"Ecuador", "Quito", "South America", "455502", "10600000"},
                        new String[]{"El Salvador", "San Salvador", "North America", "20865", "5300000"},
                        new String[]{"Guyana", "Georgetown", "South America", "214969", "800000"},

                };

        //Add a table
        Table table = section.addTable(true);
        table.resetCells(data.length + 1, header.length);

        //Set the first row as table header
        TableRow row = table.getRows().get(0);
        row.isHeader(true);
        row.setHeight(20);
        row.setHeightType(TableRowHeightType.Exactly);
        for (int j = 0; j < row.getCells().getCount(); j++) {
            row.getCells().get(j).getCellFormat().getShading().setBackgroundPatternColor(Color.gray);
        }
        for (int i = 0; i < header.length; i++) {
            row.getCells().get(i).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
            Paragraph p = row.getCells().get(i).addParagraph();
            p.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
            TextRange txtRange = p.appendText(header[i]);
            txtRange.getCharacterFormat().setBold(true);
        }

        //Add data to the rest of rows
        for (int r = 0; r < data.length; r++) {
            TableRow dataRow = table.getRows().get(r + 1);
            dataRow.setHeight(25);
            dataRow.setHeightType(TableRowHeightType.Exactly);
            for (int c = 0; c < dataRow.getCells().getCount(); c++) {
                dataRow.getCells().get(c).getCellFormat().getShading().setBackgroundPatternColor(Color.white);
            }
            for (int c = 0; c < data[r].length; c++) {
                dataRow.getCells().get(c).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
                dataRow.getCells().get(c).addParagraph().appendText(data[r][c]);
            }
        }

        //Set background color for cells
        for (int j = 1; j < table.getRows().getCount(); j++) {
            if (j % 2 == 0) {
                TableRow row2 = table.getRows().get(j);
                for (int f = 0; f < row2.getCells().getCount(); f++) {
                    row2.getCells().get(f).getCellFormat().getShading().setBackgroundPatternColor(new Color(173, 216, 230));
                }
            }
        }

        //Save to file
        document.saveToFile("output/CreateTable.docx", FileFormat.Docx_2013);
    }
}

Java: Create a Table in Word

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Java: Add or Remove Bookmarks in Word

2022-03-03 07:49:00 Written by Koohji

Bookmarks in Microsoft Word can mark text, pictures, and places in a document, allowing you to jump straight to the desired text, picture, or place without scrolling through several paragraphs or pages. This is especially useful for navigating some research papers or contracts that contain a lot of pages. In this article, you will learn how to programmatically add or remove a bookmark in a Word document using Spire.Doc for Java.

Install Spire.Doc for Java

First of all, you're required to add the Spire.Doc.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use 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>14.1.3</version>
    </dependency>
</dependencies>

Add a Bookmarks to an Existing Word Document

The detailed steps are as follows:

  • Create a Document instance.
  • Load a sample Word document using Document.loadFromFile() method.
  • Get the first section using Document.getSections().get() method.
  • Get a specified paragraph using Section.getParagraphs().get() method.
  • Append the start of the bookmark with specified name to the specified paragraph using Paragraph.appendBookmarkStart(java.lang.String name) method.
  • Append the end of the bookmark with specified name to the specified paragraph using Paragraph.appendBookmarkEnd(java.lang.String name) method.
  • Save the document to another file using Document. saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;

public class InsertBookmark {

    public static void main(String[] args) {

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

        //Load a sample Word file
        doc.loadFromFile("sample.docx");

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

        //Insert a bookmark with specified name into the specified paragraphs
        section.getParagraphs().get(7).appendBookmarkStart("ConversionFunction");
        section.getParagraphs().get(16).appendBookmarkEnd("ConversionFunction");


        //Save the document
        doc.saveToFile("AddBookmark.docx", FileFormat.Docx_2013);
    }
}

Java: Add or Remove Bookmarks in Word

Remove an Existing Bookmark in a Word Document

The detailed steps are as follows:

  • Create a Document instance.
  • Load a sample Word document using Document.loadFromFile() method.
  • Get a specified bookmark by its index using Document.getBookmarks().get() method.
  • Remove the specified bookmark using Document.getBookmarks().remove() method.
  • Save the document to another file using Document.saveToFile() method.
  • Java
import com.spire.doc.Bookmark;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;

public class RemoveBookmark {

    public static void main(String[] args) {

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

        //Load a sample Word file
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\AddBookmark.docx");

        //Get bookmark by its index
        Bookmark bookmark = doc.getBookmarks().get(0);

        //Remove the bookmark
        doc.getBookmarks().remove(bookmark);

        //Save the document.
        doc.saveToFile("RemoveBookmark.docx", FileFormat.Docx);
    }
}

Java: Add or Remove Bookmarks in Word

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

page 67