public class HeaderFooter extends Story
To learn more, visit the Working with Headers and Footers documentation article.
Remarks:
HeaderFooter can contain Paragraph and Table child nodes.
HeaderFooter is a section-level node and can only be a child of Section. There can only be one HeaderFooter of each getHeaderFooterType() in a Section.
If Section does not have a HeaderFooter of a specific type or the HeaderFooter has no child nodes, this header/footer is considered linked to the header/footer of the same type of the previous section in Microsoft Word.
When HeaderFooter contains at least one Paragraph, it is no longer considered linked to previous in Microsoft Word.
Examples:
Shows how to replace text in a document's footer.
Document doc = new Document(getMyDir() + "Footer.docx");
HeaderFooterCollection headersFooters = doc.getFirstSection().getHeadersFooters();
HeaderFooter footer = headersFooters.getByHeaderFooterType(HeaderFooterType.FOOTER_PRIMARY);
FindReplaceOptions options = new FindReplaceOptions();
options.setMatchCase(false);
options.setFindWholeWordsOnly(false);
int currentYear = Calendar.YEAR;
footer.getRange().replace("(C) 2006 Aspose Pty Ltd.", MessageFormat.format("Copyright (C) {0} by Aspose Pty Ltd.", currentYear), options);
doc.save(getArtifactsDir() + "HeaderFooter.ReplaceText.docx");
Shows how to delete all footers from a document.
Document doc = new Document(getMyDir() + "Header and footer types.docx");
// Iterate through each section and remove footers of every kind.
for (Section section : doc.getSections()) {
// There are three kinds of footer and header types.
// 1 - The "First" header/footer, which only appears on the first page of a section.
HeaderFooter footer = section.getHeadersFooters().getByHeaderFooterType(HeaderFooterType.FOOTER_FIRST);
if (footer != null) {
footer.remove();
}
// 2 - The "Primary" header/footer, which appears on odd pages.
footer = section.getHeadersFooters().getByHeaderFooterType(HeaderFooterType.FOOTER_PRIMARY);
if (footer != null) {
footer.remove();
}
// 3 - The "Even" header/footer, which appears on even pages.
footer = section.getHeadersFooters().getByHeaderFooterType(HeaderFooterType.FOOTER_EVEN);
if (footer != null) {
footer.remove();
}
Assert.assertEquals(0, IterableUtils.countMatches(section.getHeadersFooters(), s -> !s.isHeader()));
}
doc.save(getArtifactsDir() + "HeaderFooter.RemoveFooters.docx");
Shows how to create a header and a footer.
Document doc = new Document();
// Create a header and append a paragraph to it. The text in that paragraph
// will appear at the top of every page of this section, above the main body text.
HeaderFooter header = new HeaderFooter(doc, HeaderFooterType.HEADER_PRIMARY);
doc.getFirstSection().getHeadersFooters().add(header);
Paragraph para = header.appendParagraph("My header.");
Assert.assertTrue(header.isHeader());
Assert.assertTrue(para.isEndOfHeaderFooter());
// Create a footer and append a paragraph to it. The text in that paragraph
// will appear at the bottom of every page of this section, below the main body text.
HeaderFooter footer = new HeaderFooter(doc, HeaderFooterType.FOOTER_PRIMARY);
doc.getFirstSection().getHeadersFooters().add(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.Create.docx");
| Constructor and Description |
|---|
HeaderFooter(DocumentBase doc,
int headerFooterType)
Initializes a new instance of this class.
|
| Modifier and Type | Method and Description |
|---|---|
boolean |
accept(DocumentVisitor visitor)
Accepts a visitor.
|
int |
acceptEnd(DocumentVisitor visitor)
Accepts a visitor for visiting the end of the header.
|
int |
acceptStart(DocumentVisitor visitor)
Accepts a visitor for visiting the start of the header.
|
int |
getHeaderFooterType()
Gets the type of this header/footer.
|
int |
getNodeType()
Returns
NodeType.HEADER_FOOTER. |
Section |
getParentSection()
Gets the parent section of this story.
|
boolean |
isHeader()
True if this
HeaderFooter object is a header. |
boolean |
isLinkedToPrevious()
True if this header or footer is linked to the corresponding header or footer in the previous section.
|
void |
isLinkedToPrevious(boolean value)
True if this header or footer is linked to the corresponding header or footer in the previous section.
|
appendParagraph, deleteShapes, getFirstParagraph, getLastParagraph, getParagraphs, getStoryType, getTablesacceptChildren, acceptCore, appendChild, coreRemoveSelfOnly, getChild, getChildNodes, getContainer, getCount, getCurrentNode, getFirstChild, getLastChild, getNextMatchingNode, getText, hasChildNodes, indexOf, insertAfter, insertBefore, isComposite, iterator, prependChild, removeAllChildren, removeChild, removeSmartTags, selectNodes, selectSingleNodedeepClone, getAncestor, getAncestor, getCustomNodeId, getDocument, getNextSibling, getParentNode, getPreviousSibling, getRange, memberwiseClone, nextPreOrder, nodeTypeToString, previousPreOrder, remove, setCustomNodeId, toString, toString, toString, visitorActionToBoolpublic HeaderFooter(DocumentBase doc, int headerFooterType)
public int getNodeType()
NodeType.HEADER_FOOTER.
Examples:
Shows how to iterate through the children of a composite node.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.write("Section 1");
builder.moveToHeaderFooter(HeaderFooterType.HEADER_PRIMARY);
builder.write("Primary header");
builder.moveToHeaderFooter(HeaderFooterType.FOOTER_PRIMARY);
builder.write("Primary footer");
Section section = doc.getFirstSection();
// A Section is a composite node and can contain child nodes,
// but only if those child nodes are of a "Body" or "HeaderFooter" node type.
for (Node node : section) {
switch (node.getNodeType()) {
case NodeType.BODY: {
Body body = (Body) node;
System.out.println("Body:");
System.out.println("\t\"{body.GetText().Trim()}\"");
break;
}
case NodeType.HEADER_FOOTER: {
HeaderFooter headerFooter = (HeaderFooter) node;
System.out.println("HeaderFooter type: {headerFooter.HeaderFooterType}:");
System.out.println("\t\"{headerFooter.GetText().Trim()}\"");
break;
}
default: {
throw new Exception("Unexpected node type in a section.");
}
}
}
getNodeType in class NodeNodeType.HEADER_FOOTER. The returned value is one of NodeType constants.public Section getParentSection()
Remarks:
getParentSection() is equivalent to Node.getParentNode() casted to Section.
Examples:
Shows how to link headers and footers between sections.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
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");
// Move to the first section and create a header and a footer. By default,
// the header and the footer will only appear on pages in the section that contains them.
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.");
// We can link a section's headers/footers to the previous section's headers/footers
// to allow the linking section to display the linked section's headers/footers.
doc.getSections().get(1).getHeadersFooters().linkToPrevious(true);
// Each section will still have its own header/footer objects. When we link sections,
// the linking section will display the linked section's header/footers while keeping its own.
Assert.assertNotEquals(doc.getSections().get(0).getHeadersFooters().get(0), doc.getSections().get(1).getHeadersFooters().get(0));
Assert.assertNotEquals(doc.getSections().get(0).getHeadersFooters().get(0).getParentSection(), doc.getSections().get(1).getHeadersFooters().get(0).getParentSection());
// Link the headers/footers of the third section to the headers/footers of the second section.
// The second section already links to the first section's header/footers,
// so linking to the second section will create a link chain.
// The first, second, and now the third sections will all display the first section's headers.
doc.getSections().get(2).getHeadersFooters().linkToPrevious(true);
// We can un-link a previous section's header/footers by passing "false" when calling the LinkToPrevious method.
doc.getSections().get(2).getHeadersFooters().linkToPrevious(false);
// We can also select only a specific type of header/footer to link using this method.
// The third section now will have the same footer as the second and first sections, but not the header.
doc.getSections().get(2).getHeadersFooters().linkToPrevious(HeaderFooterType.FOOTER_PRIMARY, true);
// The first section's header/footers cannot link themselves to anything because there is no previous section.
Assert.assertEquals(2, doc.getSections().get(0).getHeadersFooters().getCount());
Assert.assertEquals(0, IterableUtils.countMatches(doc.getSections().get(0).getHeadersFooters(), s -> s.isLinkedToPrevious()));
// All the second section's header/footers are linked to the first section's headers/footers.
Assert.assertEquals(6, doc.getSections().get(1).getHeadersFooters().getCount());
Assert.assertEquals(6, IterableUtils.countMatches(doc.getSections().get(1).getHeadersFooters(), s -> s.isLinkedToPrevious()));
// In the third section, only the footer is linked to the first section's footer via the second section.
Assert.assertEquals(6, doc.getSections().get(2).getHeadersFooters().getCount());
Assert.assertEquals(1, IterableUtils.countMatches(doc.getSections().get(2).getHeadersFooters(), s -> s.isLinkedToPrevious()));
Assert.assertTrue(doc.getSections().get(2).getHeadersFooters().get(3).isLinkedToPrevious());
doc.save(getArtifactsDir() + "HeaderFooter.Link.docx");
public int getHeaderFooterType()
Examples:
Shows how to create a header and a footer.
Document doc = new Document();
// Create a header and append a paragraph to it. The text in that paragraph
// will appear at the top of every page of this section, above the main body text.
HeaderFooter header = new HeaderFooter(doc, HeaderFooterType.HEADER_PRIMARY);
doc.getFirstSection().getHeadersFooters().add(header);
Paragraph para = header.appendParagraph("My header.");
Assert.assertTrue(header.isHeader());
Assert.assertTrue(para.isEndOfHeaderFooter());
// Create a footer and append a paragraph to it. The text in that paragraph
// will appear at the bottom of every page of this section, below the main body text.
HeaderFooter footer = new HeaderFooter(doc, HeaderFooterType.FOOTER_PRIMARY);
doc.getFirstSection().getHeadersFooters().add(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.Create.docx");
HeaderFooterType constants.public boolean isHeader()
HeaderFooter object is a header.
Examples:
Shows how to create a header and a footer.
Document doc = new Document();
// Create a header and append a paragraph to it. The text in that paragraph
// will appear at the top of every page of this section, above the main body text.
HeaderFooter header = new HeaderFooter(doc, HeaderFooterType.HEADER_PRIMARY);
doc.getFirstSection().getHeadersFooters().add(header);
Paragraph para = header.appendParagraph("My header.");
Assert.assertTrue(header.isHeader());
Assert.assertTrue(para.isEndOfHeaderFooter());
// Create a footer and append a paragraph to it. The text in that paragraph
// will appear at the bottom of every page of this section, below the main body text.
HeaderFooter footer = new HeaderFooter(doc, HeaderFooterType.FOOTER_PRIMARY);
doc.getFirstSection().getHeadersFooters().add(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.Create.docx");
boolean value.public boolean isLinkedToPrevious()
Remarks:
Default is true.
Note, when your link a header or footer, its contents is cleared.
Examples:
Shows how to link headers and footers between sections.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
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");
// Move to the first section and create a header and a footer. By default,
// the header and the footer will only appear on pages in the section that contains them.
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.");
// We can link a section's headers/footers to the previous section's headers/footers
// to allow the linking section to display the linked section's headers/footers.
doc.getSections().get(1).getHeadersFooters().linkToPrevious(true);
// Each section will still have its own header/footer objects. When we link sections,
// the linking section will display the linked section's header/footers while keeping its own.
Assert.assertNotEquals(doc.getSections().get(0).getHeadersFooters().get(0), doc.getSections().get(1).getHeadersFooters().get(0));
Assert.assertNotEquals(doc.getSections().get(0).getHeadersFooters().get(0).getParentSection(), doc.getSections().get(1).getHeadersFooters().get(0).getParentSection());
// Link the headers/footers of the third section to the headers/footers of the second section.
// The second section already links to the first section's header/footers,
// so linking to the second section will create a link chain.
// The first, second, and now the third sections will all display the first section's headers.
doc.getSections().get(2).getHeadersFooters().linkToPrevious(true);
// We can un-link a previous section's header/footers by passing "false" when calling the LinkToPrevious method.
doc.getSections().get(2).getHeadersFooters().linkToPrevious(false);
// We can also select only a specific type of header/footer to link using this method.
// The third section now will have the same footer as the second and first sections, but not the header.
doc.getSections().get(2).getHeadersFooters().linkToPrevious(HeaderFooterType.FOOTER_PRIMARY, true);
// The first section's header/footers cannot link themselves to anything because there is no previous section.
Assert.assertEquals(2, doc.getSections().get(0).getHeadersFooters().getCount());
Assert.assertEquals(0, IterableUtils.countMatches(doc.getSections().get(0).getHeadersFooters(), s -> s.isLinkedToPrevious()));
// All the second section's header/footers are linked to the first section's headers/footers.
Assert.assertEquals(6, doc.getSections().get(1).getHeadersFooters().getCount());
Assert.assertEquals(6, IterableUtils.countMatches(doc.getSections().get(1).getHeadersFooters(), s -> s.isLinkedToPrevious()));
// In the third section, only the footer is linked to the first section's footer via the second section.
Assert.assertEquals(6, doc.getSections().get(2).getHeadersFooters().getCount());
Assert.assertEquals(1, IterableUtils.countMatches(doc.getSections().get(2).getHeadersFooters(), s -> s.isLinkedToPrevious()));
Assert.assertTrue(doc.getSections().get(2).getHeadersFooters().get(3).isLinkedToPrevious());
doc.save(getArtifactsDir() + "HeaderFooter.Link.docx");
boolean value.public void isLinkedToPrevious(boolean value)
Remarks:
Default is true.
Note, when your link a header or footer, its contents is cleared.
Examples:
Shows how to link headers and footers between sections.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
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");
// Move to the first section and create a header and a footer. By default,
// the header and the footer will only appear on pages in the section that contains them.
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.");
// We can link a section's headers/footers to the previous section's headers/footers
// to allow the linking section to display the linked section's headers/footers.
doc.getSections().get(1).getHeadersFooters().linkToPrevious(true);
// Each section will still have its own header/footer objects. When we link sections,
// the linking section will display the linked section's header/footers while keeping its own.
Assert.assertNotEquals(doc.getSections().get(0).getHeadersFooters().get(0), doc.getSections().get(1).getHeadersFooters().get(0));
Assert.assertNotEquals(doc.getSections().get(0).getHeadersFooters().get(0).getParentSection(), doc.getSections().get(1).getHeadersFooters().get(0).getParentSection());
// Link the headers/footers of the third section to the headers/footers of the second section.
// The second section already links to the first section's header/footers,
// so linking to the second section will create a link chain.
// The first, second, and now the third sections will all display the first section's headers.
doc.getSections().get(2).getHeadersFooters().linkToPrevious(true);
// We can un-link a previous section's header/footers by passing "false" when calling the LinkToPrevious method.
doc.getSections().get(2).getHeadersFooters().linkToPrevious(false);
// We can also select only a specific type of header/footer to link using this method.
// The third section now will have the same footer as the second and first sections, but not the header.
doc.getSections().get(2).getHeadersFooters().linkToPrevious(HeaderFooterType.FOOTER_PRIMARY, true);
// The first section's header/footers cannot link themselves to anything because there is no previous section.
Assert.assertEquals(2, doc.getSections().get(0).getHeadersFooters().getCount());
Assert.assertEquals(0, IterableUtils.countMatches(doc.getSections().get(0).getHeadersFooters(), s -> s.isLinkedToPrevious()));
// All the second section's header/footers are linked to the first section's headers/footers.
Assert.assertEquals(6, doc.getSections().get(1).getHeadersFooters().getCount());
Assert.assertEquals(6, IterableUtils.countMatches(doc.getSections().get(1).getHeadersFooters(), s -> s.isLinkedToPrevious()));
// In the third section, only the footer is linked to the first section's footer via the second section.
Assert.assertEquals(6, doc.getSections().get(2).getHeadersFooters().getCount());
Assert.assertEquals(1, IterableUtils.countMatches(doc.getSections().get(2).getHeadersFooters(), s -> s.isLinkedToPrevious()));
Assert.assertTrue(doc.getSections().get(2).getHeadersFooters().get(3).isLinkedToPrevious());
doc.save(getArtifactsDir() + "HeaderFooter.Link.docx");
value - The corresponding boolean value.public boolean accept(DocumentVisitor visitor) throws java.lang.Exception
Remarks:
Enumerates over this node and all of its children. Each node calls a corresponding method on DocumentVisitor.
For more info see the Visitor design pattern.
Calls DocumentVisitor.visitHeaderFooterStart(com.aspose.words.HeaderFooter), then calls Node.accept(com.aspose.words.DocumentVisitor) for all child nodes of the section and calls DocumentVisitor.visitHeaderFooterEnd(com.aspose.words.HeaderFooter) at the end.
Examples:
Shows how to print the node structure of every header and footer in a document.
public void headerFooterToText() throws Exception {
Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx");
HeaderFooterStructurePrinter visitor = new HeaderFooterStructurePrinter();
// When we get a composite node to accept a document visitor, the visitor visits the accepting node,
// and then traverses all the node's children in a depth-first manner.
// The visitor can read and modify each visited node.
doc.accept(visitor);
System.out.println(visitor.getText());
// An alternative way of accessing a document's header/footers section-by-section is by accessing the collection.
HeaderFooter[] headerFooters = doc.getFirstSection().getHeadersFooters().toArray();
Assert.assertEquals(3, headerFooters.length);
}
/// <summary>
/// Traverses a node's non-binary tree of child nodes.
/// Creates a map in the form of a string of all encountered HeaderFooter nodes and their children.
/// </summary>
public static class HeaderFooterStructurePrinter extends DocumentVisitor {
public HeaderFooterStructurePrinter() {
mBuilder = new StringBuilder();
mVisitorIsInsideHeaderFooter = false;
}
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 after all the child nodes of a HeaderFooter node have been visited.
/// </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 final StringBuilder mBuilder;
}
accept in class Nodevisitor - The visitor that will visit the nodes.DocumentVisitor stopped the operation before visiting all nodes.java.lang.Exceptionpublic int acceptStart(DocumentVisitor visitor) throws java.lang.Exception
Examples:
Shows how to print the node structure of every header and footer in a document.
public void headerFooterToText() throws Exception {
Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx");
HeaderFooterStructurePrinter visitor = new HeaderFooterStructurePrinter();
// When we get a composite node to accept a document visitor, the visitor visits the accepting node,
// and then traverses all the node's children in a depth-first manner.
// The visitor can read and modify each visited node.
doc.accept(visitor);
System.out.println(visitor.getText());
// An alternative way of accessing a document's header/footers section-by-section is by accessing the collection.
HeaderFooter[] headerFooters = doc.getFirstSection().getHeadersFooters().toArray();
Assert.assertEquals(3, headerFooters.length);
}
/// <summary>
/// Traverses a node's non-binary tree of child nodes.
/// Creates a map in the form of a string of all encountered HeaderFooter nodes and their children.
/// </summary>
public static class HeaderFooterStructurePrinter extends DocumentVisitor {
public HeaderFooterStructurePrinter() {
mBuilder = new StringBuilder();
mVisitorIsInsideHeaderFooter = false;
}
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 after all the child nodes of a HeaderFooter node have been visited.
/// </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 final StringBuilder mBuilder;
}
acceptStart in class CompositeNodevisitor - The document visitor.VisitorAction constants.java.lang.Exceptionpublic int acceptEnd(DocumentVisitor visitor) throws java.lang.Exception
Examples:
Shows how to print the node structure of every header and footer in a document.
public void headerFooterToText() throws Exception {
Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx");
HeaderFooterStructurePrinter visitor = new HeaderFooterStructurePrinter();
// When we get a composite node to accept a document visitor, the visitor visits the accepting node,
// and then traverses all the node's children in a depth-first manner.
// The visitor can read and modify each visited node.
doc.accept(visitor);
System.out.println(visitor.getText());
// An alternative way of accessing a document's header/footers section-by-section is by accessing the collection.
HeaderFooter[] headerFooters = doc.getFirstSection().getHeadersFooters().toArray();
Assert.assertEquals(3, headerFooters.length);
}
/// <summary>
/// Traverses a node's non-binary tree of child nodes.
/// Creates a map in the form of a string of all encountered HeaderFooter nodes and their children.
/// </summary>
public static class HeaderFooterStructurePrinter extends DocumentVisitor {
public HeaderFooterStructurePrinter() {
mBuilder = new StringBuilder();
mVisitorIsInsideHeaderFooter = false;
}
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 after all the child nodes of a HeaderFooter node have been visited.
/// </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 final StringBuilder mBuilder;
}
acceptEnd in class CompositeNodevisitor - The document visitor.VisitorAction constants.java.lang.Exception