com.aspose.words

Class HeaderFooterCollection

  • java.lang.Object
  • All Implemented Interfaces:
    java.lang.Iterable
    public class HeaderFooterCollection 
    extends NodeCollection

Provides typed access to HeaderFooter nodes of a Section.

There can be maximum of one HeaderFooter

of each HeaderFooterType per Section.

HeaderFooter objects can occur in any order in the collection.

Example:

Deletes all footers from all sections, but leaves headers intact.
Document doc = new Document(getMyDir() + "HeaderFooter.RemoveFooters.doc");

for (Section section : doc.getSections()) {
    // Up to three different footers are possible in a section (for first, even and odd pages).
    // We check and delete all of them.
    HeaderFooter footer;

    footer = section.getHeadersFooters().getByHeaderFooterType(HeaderFooterType.FOOTER_FIRST);
    if (footer != null) {
        footer.remove();
    }

    // Primary footer is the footer used for odd pages.
    footer = section.getHeadersFooters().getByHeaderFooterType(HeaderFooterType.FOOTER_PRIMARY);
    if (footer != null) {
        footer.remove();
    }

    footer = section.getHeadersFooters().getByHeaderFooterType(HeaderFooterType.FOOTER_EVEN);
    if (footer != null) {
        footer.remove();
    }
}

doc.save(getArtifactsDir() + "HeaderFooter.RemoveFooters.doc");

Example:

Creates a footer using the document object model and inserts it into a section.
Document doc = new Document();

HeaderFooter header = new HeaderFooter(doc, HeaderFooterType.HEADER_PRIMARY);
doc.getFirstSection().getHeadersFooters().add(header);

// Add a paragraph with text to the footer.
Paragraph para = header.appendParagraph("My header");

Assert.assertTrue(header.isHeader());
Assert.assertTrue(para.isEndOfHeaderFooter());

HeaderFooter footer = new HeaderFooter(doc, HeaderFooterType.FOOTER_PRIMARY);
doc.getFirstSection().getHeadersFooters().add(footer);

// Add a paragraph with text to the footer.
para = footer.appendParagraph("My footer");

Assert.assertFalse(footer.isHeader());
Assert.assertTrue(para.isEndOfHeaderFooter());

Assert.assertEquals(para.getParentStory(), footer);
Assert.assertEquals(para.getParentSection(), footer.getParentSection());
Assert.assertEquals(header.getParentSection(), footer.getParentSection());

doc.save(getArtifactsDir() + "HeaderFooter.CreateFooter.doc");

Property Getters/Setters Summary
intgetCount()
Gets the number of nodes in the collection.
HeaderFooterget(int index)
Retrieves a HeaderFooter at the given index.
HeaderFootergetByHeaderFooterType(int headerFooterType)
Retrieves a HeaderFooter of the specified type.
 
Method Summary
voidadd(Node node)
Adds a node to the end of the collection.
voidclear()
Removes all nodes from this collection and from the document.
booleancontains(Node node)
Determines whether a node is in the collection.
intindexOf(Node node)
Returns the zero-based index of the specified node.
voidinsert(int index, Node node)
Inserts a node into the collection at the specified index.
java.util.Iterator<Node>iterator()
voidlinkToPrevious(boolean isLinkToPrevious)
Links or unlinks all headers and footers to the corresponding headers and footers in the previous section.
voidlinkToPrevious(int headerFooterType, boolean isLinkToPrevious)
Links or unlinks the specified header or footer to the corresponding header or footer in the previous section.
voidremove(Node node)
Removes the node from the collection and from the document.
voidremoveAt(int index)
Removes the node at the specified index from the collection and from the document.
HeaderFooter[]toArray()
Copies all HeaderFoorters from the collection to a new array of HeaderFoorters.
 

    • Property Getters/Setters Detail

      • getCount

        public int getCount()
        
        Gets the number of nodes in the collection.

        Example:

        Shows how to enumerate immediate children of a CompositeNode using indexed access.
        NodeCollection children = paragraph.getChildNodes();
        for (int i = 0; i < children.getCount(); i++) {
            Node child = children.get(i);
        
            // Paragraph may contain children of various types such as runs, shapes and so on.
            if (child.getNodeType() == NodeType.RUN) {
                // Say we found the node that we want, do something useful.
                Run run = (Run) child;
                System.out.println(run.getText());
            }
        }

        Example:

        Shows how to find out if a table contains another table or if the table itself is nested inside another table.
        public void calculateDepthOfNestedTables() throws Exception {
            Document doc = new Document(getMyDir() + "Table.NestedTables.doc");
            int tableIndex = 0;
        
            for (Table table : (Iterable<Table>) doc.getChildNodes(NodeType.TABLE, true)) {
                // First lets find if any cells in the table have tables themselves as children.
                int count = getChildTableCount(table);
                System.out.println(MessageFormat.format("Table #{0} has {1} tables directly within its cells", tableIndex, count));
        
                // Now let's try the other way around, lets try find if the table is nested inside another table and at what depth.
                int tableDepth = getNestedDepthOfTable(table);
        
                if (tableDepth > 0) {
                    System.out.println(MessageFormat.format("Table #{0} is nested inside another table at depth of {1}", tableIndex, tableDepth));
                } else {
                    System.out.println(MessageFormat.format("Table #{0} is a non nested table (is not a child of another table)", tableIndex));
                }
        
                tableIndex++;
            }
        }
        
        /**
         * Calculates what level a table is nested inside other tables.
         *
         * @returns An integer containing the level the table is nested at.
         * 0 = Table is not nested inside any other table
         * 1 = Table is nested within one parent table
         * 2 = Table is nested within two parent tables etc..
         */
        private static int getNestedDepthOfTable(final Table table) {
            int depth = 0;
        
            int type = table.getNodeType();
            // The parent of the table will be a Cell, instead attempt to find a grandparent that is of type Table
            Node parent = table.getAncestor(table.getNodeType());
        
            while (parent != null) {
                // Every time we find a table a level up we increase the depth counter and then try to find an
                // ancestor of type table from the parent.
                depth++;
                parent = parent.getAncestor(Table.class);
            }
        
            return depth;
        }
        
        /**
         * Determines if a table contains any immediate child table within its cells.
         * Does not recursively traverse through those tables to check for further tables.
         *
         * @returns Returns true if at least one child cell contains a table.
         * Returns false if no cells in the table contains a table.
         */
        private static int getChildTableCount(final Table table) {
            int tableCount = 0;
            // Iterate through all child rows in the table
            for (Row row : table.getRows()) {
                // Iterate through all child cells in the row
                for (Cell cell : row.getCells()) {
                    // Retrieve the collection of child tables of this cell
                    TableCollection childTables = cell.getTables();
        
                    // If this cell has a table as a child then return true
                    if (childTables.getCount() > 0) tableCount++;
                }
            }
        
            // No cell contains a table
            return tableCount;
        }
      • get

        public HeaderFooter get(int index)
        
        Retrieves a HeaderFooter at the given index.

        The index is zero-based.

        Negative indexes are allowed and indicate access from the back of the collection. For example -1 means the last item, -2 means the second before last and so on.

        If index is greater than or equal to the number of items in the list, this returns a null reference.

        If index is negative and its absolute value is greater than the number of items in the list, this returns a null reference.

        Parameters:
        index - An index into the collection.

        Example:

        Shows how to link header/footers between sections.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        // Create three sections
        builder.write("Section 1");
        builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);
        builder.write("Section 2");
        builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);
        builder.write("Section 3");
        
        // Create a header and footer in the first section and give them text
        builder.moveToSection(0);
        
        builder.moveToHeaderFooter(HeaderFooterType.HEADER_PRIMARY);
        builder.write("This is the header, which will be displayed in sections 1 and 2.");
        
        builder.moveToHeaderFooter(HeaderFooterType.FOOTER_PRIMARY);
        builder.write("This is the footer, which will be displayed in sections 1, 2 and 3.");
        
        // If headers/footers are linked by the next section, they appear in that section also
        // The second section will display the header/footers of the first
        doc.getSections().get(1).getHeadersFooters().linkToPrevious(true);
        
        // However, the underlying headers/footers in the respective header/footer collections of the sections still remain different
        // Linking just overrides the existing headers/footers from the latter section
        Assert.assertEquals(doc.getSections().get(1).getHeadersFooters().get(0).getHeaderFooterType(), doc.getSections().get(0).getHeadersFooters().get(0).getHeaderFooterType());
        Assert.assertNotEquals(doc.getSections().get(1).getHeadersFooters().get(0).getParentSection(), doc.getSections().get(0).getHeadersFooters().get(0).getParentSection());
        Assert.assertNotEquals(doc.getSections().get(1).getHeadersFooters().get(0).getText(), doc.getSections().get(0).getHeadersFooters().get(0).getText());
        
        // Likewise, unlinking headers/footers makes them not appear
        doc.getSections().get(2).getHeadersFooters().linkToPrevious(false);
        
        // We can also choose only certain header/footer types to get linked, like the footer in this case
        // The 3rd section now won't have the same header but will have the same footer as the 2nd and 1st sections
        doc.getSections().get(2).getHeadersFooters().linkToPrevious(HeaderFooterType.FOOTER_PRIMARY, true);
        
        // The first section's header/footers can't link themselves to anything because there is no previous section
        Assert.assertEquals(doc.getSections().get(0).getHeadersFooters().getCount(), 2);
        Assert.assertFalse(doc.getSections().get(0).getHeadersFooters().get(0).isLinkedToPrevious());
        Assert.assertFalse(doc.getSections().get(0).getHeadersFooters().get(1).isLinkedToPrevious());
        
        // All of the second section's header/footers are linked to those of the first
        Assert.assertEquals(doc.getSections().get(1).getHeadersFooters().getCount(), 6);
        Assert.assertTrue(doc.getSections().get(1).getHeadersFooters().get(0).isLinkedToPrevious());
        Assert.assertTrue(doc.getSections().get(1).getHeadersFooters().get(1).isLinkedToPrevious());
        Assert.assertTrue(doc.getSections().get(1).getHeadersFooters().get(2).isLinkedToPrevious());
        Assert.assertTrue(doc.getSections().get(1).getHeadersFooters().get(3).isLinkedToPrevious());
        Assert.assertTrue(doc.getSections().get(1).getHeadersFooters().get(4).isLinkedToPrevious());
        Assert.assertTrue(doc.getSections().get(1).getHeadersFooters().get(5).isLinkedToPrevious());
        
        // In the third section, only the footer we explicitly linked is linked to that of the second, and consequently the first section
        Assert.assertEquals(doc.getSections().get(2).getHeadersFooters().getCount(), 6);
        Assert.assertFalse(doc.getSections().get(2).getHeadersFooters().get(0).isLinkedToPrevious());
        Assert.assertFalse(doc.getSections().get(2).getHeadersFooters().get(1).isLinkedToPrevious());
        Assert.assertFalse(doc.getSections().get(2).getHeadersFooters().get(2).isLinkedToPrevious());
        Assert.assertTrue(doc.getSections().get(2).getHeadersFooters().get(3).isLinkedToPrevious());
        Assert.assertFalse(doc.getSections().get(2).getHeadersFooters().get(4).isLinkedToPrevious());
        Assert.assertFalse(doc.getSections().get(2).getHeadersFooters().get(5).isLinkedToPrevious());
        
        doc.save(getArtifactsDir() + "HeaderFooter.HeaderFooterLink.docx");
      • getByHeaderFooterType

        public HeaderFooter getByHeaderFooterType(int headerFooterType)
        
        Retrieves a HeaderFooter of the specified type. Returns null if the header/footer of the specified type is not found.
        Parameters:
        headerFooterType - A HeaderFooterType value. A HeaderFooterType value that specifies the type of the header/footer to retrieve.

        Example:

        Deletes all footers from all sections, but leaves headers intact.
        Document doc = new Document(getMyDir() + "HeaderFooter.RemoveFooters.doc");
        
        for (Section section : doc.getSections()) {
            // Up to three different footers are possible in a section (for first, even and odd pages).
            // We check and delete all of them.
            HeaderFooter footer;
        
            footer = section.getHeadersFooters().getByHeaderFooterType(HeaderFooterType.FOOTER_FIRST);
            if (footer != null) {
                footer.remove();
            }
        
            // Primary footer is the footer used for odd pages.
            footer = section.getHeadersFooters().getByHeaderFooterType(HeaderFooterType.FOOTER_PRIMARY);
            if (footer != null) {
                footer.remove();
            }
        
            footer = section.getHeadersFooters().getByHeaderFooterType(HeaderFooterType.FOOTER_EVEN);
            if (footer != null) {
                footer.remove();
            }
        }
        
        doc.save(getArtifactsDir() + "HeaderFooter.RemoveFooters.doc");

        Example:

        Shows how to replace text in the document footer.
        // Open the template document, containing obsolete copyright information in the footer.
        Document doc = new Document(getMyDir() + "HeaderFooter.ReplaceText.doc");
        
        HeaderFooterCollection headersFooters = doc.getFirstSection().getHeadersFooters();
        HeaderFooter footer = headersFooters.getByHeaderFooterType(HeaderFooterType.FOOTER_PRIMARY);
        
        FindReplaceOptions options = new FindReplaceOptions();
        options.setMatchCase(false);
        options.setFindWholeWordsOnly(false);
        
        footer.getRange().replace("(C) 2006 Aspose Pty Ltd.", "Copyright (C) 2011 by Aspose Pty Ltd.", options);
        
        doc.save(getArtifactsDir() + "HeaderFooter.ReplaceText.doc");
    • Method Detail

      • add

        public void add(Node node)
        Adds a node to the end of the collection.

        The node is inserted as a child into the node object from which the collection was created.

        If the newChild is already in the tree, it is first removed.

        If the node being inserted was created from another document, you should use DocumentBase.importNode(com.aspose.words.Node,boolean,int) to import the node to the current document. The imported node can then be inserted into the current document.

        Parameters:
        node - The node to be added to the end of the collection.

        Example:

        Shows how to add a section to the end of the document.
        Document doc = new Document(getMyDir() + "Document.doc");
        Section sectionToAdd = new Section(doc);
        doc.getSections().add(sectionToAdd);
      • clear

        public void clear()
        Removes all nodes from this collection and from the document.

        Example:

        Shows how to remove all sections from a document.
        Document doc = new Document(getMyDir() + "Document.doc");
        doc.getSections().clear();
      • contains

        public boolean contains(Node node)
        Determines whether a node is in the collection.

        This method performs a linear search; therefore, the average execution time is proportional to Count.

        Parameters:
        node - The node to locate.
        Returns:
        True if item is found in the collection; otherwise, false.

        Example:

        Shows how to work with a NodeCollection.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        // The normal way to insert Runs into a document is to add text using a DocumentBuilder
        builder.write("Run 1. ");
        builder.write("Run 2. ");
        
        // Every .Write() invocation creates a new Run, which is added to the parent Paragraph's RunCollection
        RunCollection runs = doc.getFirstSection().getBody().getFirstParagraph().getRuns();
        Assert.assertEquals(runs.getCount(), 2);
        
        // We can insert a node into the RunCollection manually to achieve the same effect
        Run newRun = new Run(doc, "Run 3. ");
        runs.insert(3, newRun);
        
        Assert.assertTrue(runs.contains(newRun));
        Assert.assertEquals("Run 1. Run 2. Run 3.", doc.getText().trim());
        
        // Text can also be deleted from the document by accessing individual Runs via the RunCollection and editing or removing them
        Run run = runs.get(1);
        runs.remove(run);
        Assert.assertEquals("Run 1. Run 3.", doc.getText().trim());
        
        Assert.assertNotNull(run);
        Assert.assertFalse(runs.contains(run));
      • indexOf

        public int indexOf(Node node)
        Returns the zero-based index of the specified node.

        This method performs a linear search; therefore, the average execution time is proportional to Count.

        Parameters:
        node - The node to locate.
        Returns:
        The zero-based index of the node within the collection, if found; otherwise, -1.

        Example:

        Retrieves the index of a table in the document.
        NodeCollection allTables = doc.getChildNodes(NodeType.TABLE, true);
        int tableIndex = allTables.indexOf(table);
      • insert

        public void insert(int index, Node node)
        Inserts a node into the collection at the specified index.

        The node is inserted as a child into the node object from which the collection was created.

        If the index is equal to or greater than Count, the node is added at the end of the collection.

        If the index is negative and its absolute value is greater than Count, the node is added at the end of the collection.

        If the newChild is already in the tree, it is first removed.

        If the node being inserted was created from another document, you should use DocumentBase.importNode(com.aspose.words.Node,boolean,int) to import the node to the current document. The imported node can then be inserted into the current document.

        Parameters:
        index - The zero-based index of the node. Negative indexes are allowed and indicate access from the back of the list. For example -1 means the last node, -2 means the second before last and so on.
        node - The node to insert.

        Example:

        Shows how to work with a NodeCollection.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        // The normal way to insert Runs into a document is to add text using a DocumentBuilder
        builder.write("Run 1. ");
        builder.write("Run 2. ");
        
        // Every .Write() invocation creates a new Run, which is added to the parent Paragraph's RunCollection
        RunCollection runs = doc.getFirstSection().getBody().getFirstParagraph().getRuns();
        Assert.assertEquals(runs.getCount(), 2);
        
        // We can insert a node into the RunCollection manually to achieve the same effect
        Run newRun = new Run(doc, "Run 3. ");
        runs.insert(3, newRun);
        
        Assert.assertTrue(runs.contains(newRun));
        Assert.assertEquals("Run 1. Run 2. Run 3.", doc.getText().trim());
        
        // Text can also be deleted from the document by accessing individual Runs via the RunCollection and editing or removing them
        Run run = runs.get(1);
        runs.remove(run);
        Assert.assertEquals("Run 1. Run 3.", doc.getText().trim());
        
        Assert.assertNotNull(run);
        Assert.assertFalse(runs.contains(run));
      • iterator

        public java.util.Iterator<Node> iterator()
      • linkToPrevious

        public void linkToPrevious(boolean isLinkToPrevious)
        Links or unlinks all headers and footers to the corresponding headers and footers in the previous section.

        If any of the headers or footers do not exist, creates them automatically.

        Parameters:
        isLinkToPrevious - True to link the headers and footers to the previous section; false to unlink them.

        Example:

        Shows how to link header/footers between sections.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        // Create three sections
        builder.write("Section 1");
        builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);
        builder.write("Section 2");
        builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);
        builder.write("Section 3");
        
        // Create a header and footer in the first section and give them text
        builder.moveToSection(0);
        
        builder.moveToHeaderFooter(HeaderFooterType.HEADER_PRIMARY);
        builder.write("This is the header, which will be displayed in sections 1 and 2.");
        
        builder.moveToHeaderFooter(HeaderFooterType.FOOTER_PRIMARY);
        builder.write("This is the footer, which will be displayed in sections 1, 2 and 3.");
        
        // If headers/footers are linked by the next section, they appear in that section also
        // The second section will display the header/footers of the first
        doc.getSections().get(1).getHeadersFooters().linkToPrevious(true);
        
        // However, the underlying headers/footers in the respective header/footer collections of the sections still remain different
        // Linking just overrides the existing headers/footers from the latter section
        Assert.assertEquals(doc.getSections().get(1).getHeadersFooters().get(0).getHeaderFooterType(), doc.getSections().get(0).getHeadersFooters().get(0).getHeaderFooterType());
        Assert.assertNotEquals(doc.getSections().get(1).getHeadersFooters().get(0).getParentSection(), doc.getSections().get(0).getHeadersFooters().get(0).getParentSection());
        Assert.assertNotEquals(doc.getSections().get(1).getHeadersFooters().get(0).getText(), doc.getSections().get(0).getHeadersFooters().get(0).getText());
        
        // Likewise, unlinking headers/footers makes them not appear
        doc.getSections().get(2).getHeadersFooters().linkToPrevious(false);
        
        // We can also choose only certain header/footer types to get linked, like the footer in this case
        // The 3rd section now won't have the same header but will have the same footer as the 2nd and 1st sections
        doc.getSections().get(2).getHeadersFooters().linkToPrevious(HeaderFooterType.FOOTER_PRIMARY, true);
        
        // The first section's header/footers can't link themselves to anything because there is no previous section
        Assert.assertEquals(doc.getSections().get(0).getHeadersFooters().getCount(), 2);
        Assert.assertFalse(doc.getSections().get(0).getHeadersFooters().get(0).isLinkedToPrevious());
        Assert.assertFalse(doc.getSections().get(0).getHeadersFooters().get(1).isLinkedToPrevious());
        
        // All of the second section's header/footers are linked to those of the first
        Assert.assertEquals(doc.getSections().get(1).getHeadersFooters().getCount(), 6);
        Assert.assertTrue(doc.getSections().get(1).getHeadersFooters().get(0).isLinkedToPrevious());
        Assert.assertTrue(doc.getSections().get(1).getHeadersFooters().get(1).isLinkedToPrevious());
        Assert.assertTrue(doc.getSections().get(1).getHeadersFooters().get(2).isLinkedToPrevious());
        Assert.assertTrue(doc.getSections().get(1).getHeadersFooters().get(3).isLinkedToPrevious());
        Assert.assertTrue(doc.getSections().get(1).getHeadersFooters().get(4).isLinkedToPrevious());
        Assert.assertTrue(doc.getSections().get(1).getHeadersFooters().get(5).isLinkedToPrevious());
        
        // In the third section, only the footer we explicitly linked is linked to that of the second, and consequently the first section
        Assert.assertEquals(doc.getSections().get(2).getHeadersFooters().getCount(), 6);
        Assert.assertFalse(doc.getSections().get(2).getHeadersFooters().get(0).isLinkedToPrevious());
        Assert.assertFalse(doc.getSections().get(2).getHeadersFooters().get(1).isLinkedToPrevious());
        Assert.assertFalse(doc.getSections().get(2).getHeadersFooters().get(2).isLinkedToPrevious());
        Assert.assertTrue(doc.getSections().get(2).getHeadersFooters().get(3).isLinkedToPrevious());
        Assert.assertFalse(doc.getSections().get(2).getHeadersFooters().get(4).isLinkedToPrevious());
        Assert.assertFalse(doc.getSections().get(2).getHeadersFooters().get(5).isLinkedToPrevious());
        
        doc.save(getArtifactsDir() + "HeaderFooter.HeaderFooterLink.docx");
      • linkToPrevious

        public void linkToPrevious(int headerFooterType, boolean isLinkToPrevious)
        Links or unlinks the specified header or footer to the corresponding header or footer in the previous section.

        If the header or footer of the specified type does not exist, creates it automatically.

        Parameters:
        headerFooterType - A HeaderFooterType value that specifies the header or footer to link/unlink.
        isLinkToPrevious - True to link the header or footer to the previous section; false to unlink.

        Example:

        Shows how to link header/footers between sections.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        // Create three sections
        builder.write("Section 1");
        builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);
        builder.write("Section 2");
        builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);
        builder.write("Section 3");
        
        // Create a header and footer in the first section and give them text
        builder.moveToSection(0);
        
        builder.moveToHeaderFooter(HeaderFooterType.HEADER_PRIMARY);
        builder.write("This is the header, which will be displayed in sections 1 and 2.");
        
        builder.moveToHeaderFooter(HeaderFooterType.FOOTER_PRIMARY);
        builder.write("This is the footer, which will be displayed in sections 1, 2 and 3.");
        
        // If headers/footers are linked by the next section, they appear in that section also
        // The second section will display the header/footers of the first
        doc.getSections().get(1).getHeadersFooters().linkToPrevious(true);
        
        // However, the underlying headers/footers in the respective header/footer collections of the sections still remain different
        // Linking just overrides the existing headers/footers from the latter section
        Assert.assertEquals(doc.getSections().get(1).getHeadersFooters().get(0).getHeaderFooterType(), doc.getSections().get(0).getHeadersFooters().get(0).getHeaderFooterType());
        Assert.assertNotEquals(doc.getSections().get(1).getHeadersFooters().get(0).getParentSection(), doc.getSections().get(0).getHeadersFooters().get(0).getParentSection());
        Assert.assertNotEquals(doc.getSections().get(1).getHeadersFooters().get(0).getText(), doc.getSections().get(0).getHeadersFooters().get(0).getText());
        
        // Likewise, unlinking headers/footers makes them not appear
        doc.getSections().get(2).getHeadersFooters().linkToPrevious(false);
        
        // We can also choose only certain header/footer types to get linked, like the footer in this case
        // The 3rd section now won't have the same header but will have the same footer as the 2nd and 1st sections
        doc.getSections().get(2).getHeadersFooters().linkToPrevious(HeaderFooterType.FOOTER_PRIMARY, true);
        
        // The first section's header/footers can't link themselves to anything because there is no previous section
        Assert.assertEquals(doc.getSections().get(0).getHeadersFooters().getCount(), 2);
        Assert.assertFalse(doc.getSections().get(0).getHeadersFooters().get(0).isLinkedToPrevious());
        Assert.assertFalse(doc.getSections().get(0).getHeadersFooters().get(1).isLinkedToPrevious());
        
        // All of the second section's header/footers are linked to those of the first
        Assert.assertEquals(doc.getSections().get(1).getHeadersFooters().getCount(), 6);
        Assert.assertTrue(doc.getSections().get(1).getHeadersFooters().get(0).isLinkedToPrevious());
        Assert.assertTrue(doc.getSections().get(1).getHeadersFooters().get(1).isLinkedToPrevious());
        Assert.assertTrue(doc.getSections().get(1).getHeadersFooters().get(2).isLinkedToPrevious());
        Assert.assertTrue(doc.getSections().get(1).getHeadersFooters().get(3).isLinkedToPrevious());
        Assert.assertTrue(doc.getSections().get(1).getHeadersFooters().get(4).isLinkedToPrevious());
        Assert.assertTrue(doc.getSections().get(1).getHeadersFooters().get(5).isLinkedToPrevious());
        
        // In the third section, only the footer we explicitly linked is linked to that of the second, and consequently the first section
        Assert.assertEquals(doc.getSections().get(2).getHeadersFooters().getCount(), 6);
        Assert.assertFalse(doc.getSections().get(2).getHeadersFooters().get(0).isLinkedToPrevious());
        Assert.assertFalse(doc.getSections().get(2).getHeadersFooters().get(1).isLinkedToPrevious());
        Assert.assertFalse(doc.getSections().get(2).getHeadersFooters().get(2).isLinkedToPrevious());
        Assert.assertTrue(doc.getSections().get(2).getHeadersFooters().get(3).isLinkedToPrevious());
        Assert.assertFalse(doc.getSections().get(2).getHeadersFooters().get(4).isLinkedToPrevious());
        Assert.assertFalse(doc.getSections().get(2).getHeadersFooters().get(5).isLinkedToPrevious());
        
        doc.save(getArtifactsDir() + "HeaderFooter.HeaderFooterLink.docx");
      • remove

        public void remove(Node node)
        Removes the node from the collection and from the document.
        Parameters:
        node - The node to remove.

        Example:

        Shows how to work with a NodeCollection.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        // The normal way to insert Runs into a document is to add text using a DocumentBuilder
        builder.write("Run 1. ");
        builder.write("Run 2. ");
        
        // Every .Write() invocation creates a new Run, which is added to the parent Paragraph's RunCollection
        RunCollection runs = doc.getFirstSection().getBody().getFirstParagraph().getRuns();
        Assert.assertEquals(runs.getCount(), 2);
        
        // We can insert a node into the RunCollection manually to achieve the same effect
        Run newRun = new Run(doc, "Run 3. ");
        runs.insert(3, newRun);
        
        Assert.assertTrue(runs.contains(newRun));
        Assert.assertEquals("Run 1. Run 2. Run 3.", doc.getText().trim());
        
        // Text can also be deleted from the document by accessing individual Runs via the RunCollection and editing or removing them
        Run run = runs.get(1);
        runs.remove(run);
        Assert.assertEquals("Run 1. Run 3.", doc.getText().trim());
        
        Assert.assertNotNull(run);
        Assert.assertFalse(runs.contains(run));
      • removeAt

        public void removeAt(int index)
        Removes the node at the specified index from the collection and from the document.
        Parameters:
        index - The zero-based index of the node. Negative indexes are allowed and indicate access from the back of the list. For example -1 means the last node, -2 means the second before last and so on.

        Example:

        Shows how to add/remove sections in a document.
        // Open the document.
        Document doc = new Document(getMyDir() + "Section.AddRemove.doc");
        
        // This shows what is in the document originally. The document has two sections.
        System.out.println(doc.getText());
        
        // Delete the first section from the document
        doc.getSections().removeAt(0);
        
        // Duplicate the last section and append the copy to the end of the document.
        int lastSectionIdx = doc.getSections().getCount() - 1;
        Section newSection = doc.getSections().get(lastSectionIdx).deepClone();
        doc.getSections().add(newSection);
        
        // Check what the document contains after we changed it.
        System.out.println(doc.getText());
      • toArray

        public HeaderFooter[] toArray()
        Copies all HeaderFoorters from the collection to a new array of HeaderFoorters.
        Returns:
        An array of HeaderFoorters.

        Example:

        Traverse a document with a visitor that prints all header/footer nodes that it encounters.
        public void headerFooterToText() throws Exception {
            // Open the document that has headers and/or footers we want to print the info of
            Document doc = new Document(getMyDir() + "DocumentVisitor.Destination.docx");
        
            // Create an object that inherits from the DocumentVisitor class
            HeaderFooterInfoPrinter visitor = new HeaderFooterInfoPrinter();
        
            // Accepring a visitor lets it start traversing the nodes in the document, 
            // starting with the node that accepted it to then recursively visit every child
            doc.accept(visitor);
        
            // Once the visiting is complete, we can retrieve the result of the operation,
            // that in this example, has accumulated in the visitor
            System.out.println(visitor.getText());
        
            // An alternative way of visiting a document's header/footers section-by-section is by accessing the collection
            // We can also turn it into an array
            HeaderFooter[] headerFooters = doc.getFirstSection().getHeadersFooters().toArray();
            Assert.assertEquals(headerFooters.length, 6);
        }
        
        /// <summary>
        /// This Visitor implementation prints information about HeaderFooter nodes encountered in the document.
        /// </summary>
        public static class HeaderFooterInfoPrinter extends DocumentVisitor {
            public HeaderFooterInfoPrinter() {
                mBuilder = new StringBuilder();
                mVisitorIsInsideHeaderFooter = false;
            }
        
            /// <summary>
            /// Gets the plain text of the document that was accumulated by the visitor.
            /// </summary>
            public String getText() {
                return mBuilder.toString();
            }
        
            /// <summary>
            /// Called when a Run node is encountered in the document.
            /// </summary>
            public int visitRun(final Run run) {
                if (mVisitorIsInsideHeaderFooter) indentAndAppendLine("[Run] \"" + run.getText() + "\"");
        
                return VisitorAction.CONTINUE;
            }
        
            /// <summary>
            /// Called when a HeaderFooter node is encountered in the document.
            /// </summary>
            public int visitHeaderFooterStart(final HeaderFooter headerFooter) {
                indentAndAppendLine("[HeaderFooter start] HeaderFooterType: " + headerFooter.getHeaderFooterType());
                mDocTraversalDepth++;
                mVisitorIsInsideHeaderFooter = true;
        
                return VisitorAction.CONTINUE;
            }
        
            /// <summary>
            /// Called when the visiting of a HeaderFooter node is ended.
            /// </summary>
            public int visitHeaderFooterEnd(final HeaderFooter headerFooter) {
                mDocTraversalDepth--;
                indentAndAppendLine("[HeaderFooter end]");
                mVisitorIsInsideHeaderFooter = false;
        
                return VisitorAction.CONTINUE;
            }
        
            /// <summary>
            /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
            /// </summary>
            /// <param name="text"></param>
            private void indentAndAppendLine(final String text) {
                for (int i = 0; i < mDocTraversalDepth; i++) {
                    mBuilder.append("|  ");
                }
        
                mBuilder.append(text + "\r\n");
            }
        
            private boolean mVisitorIsInsideHeaderFooter;
            private int mDocTraversalDepth;
            private StringBuilder mBuilder;
        }