public class Section extends CompositeNode
To learn more, visit the Working with Sections documentation article.
Remarks:
Section can have one Body and maximum one HeaderFooter of each HeaderFooterType. Body and HeaderFooter nodes can be in any order inside Section.
A minimal valid section needs to have Body with one Paragraph.
Each section has its own set of properties that specify page size, orientation, margins etc.
You can create a copy of a section using Node.deepClone(boolean). The copy can be inserted into the same or different document.
To add, insert or remove a whole section including section break and section properties use methods of the Document.getSections() object.
To copy and insert just content of the section excluding the section break and section properties use appendContent(com.aspose.words.Section) and prependContent(com.aspose.words.Section) methods.
Examples:
Shows how to construct an Aspose.Words document by hand.
Document doc = new Document();
// A blank document contains one section, one body and one paragraph.
// Call the "RemoveAllChildren" method to remove all those nodes,
// and end up with a document node with no children.
doc.removeAllChildren();
// This document now has no composite child nodes that we can add content to.
// If we wish to edit it, we will need to repopulate its node collection.
// First, create a new section, and then append it as a child to the root document node.
Section section = new Section(doc);
doc.appendChild(section);
// Set some page setup properties for the section.
section.getPageSetup().setSectionStart(SectionStart.NEW_PAGE);
section.getPageSetup().setPaperSize(PaperSize.LETTER);
// A section needs a body, which will contain and display all its contents
// on the page between the section's header and footer.
Body body = new Body(doc);
section.appendChild(body);
// Create a paragraph, set some formatting properties, and then append it as a child to the body.
Paragraph para = new Paragraph(doc);
para.getParagraphFormat().setStyleName("Heading 1");
para.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
body.appendChild(para);
// Finally, add some content to do the document. Create a run,
// set its appearance and contents, and then append it as a child to the paragraph.
Run run = new Run(doc);
run.setText("Hello World!");
run.getFont().setColor(Color.RED);
para.appendChild(run);
Assert.assertEquals("Hello World!", doc.getText().trim());
doc.save(getArtifactsDir() + "Section.CreateManually.docx");
| Constructor and Description |
|---|
Section(DocumentBase doc)
Initializes a new instance of the Section class.
|
| Modifier and Type | Method and Description |
|---|---|
boolean |
accept(DocumentVisitor visitor)
Accepts a visitor.
|
int |
acceptEnd(DocumentVisitor visitor)
When implemented in a derived class, calls the VisitXXXEnd method of the specified document visitor.
|
int |
acceptStart(DocumentVisitor visitor)
When implemented in a derived class, calls the VisitXXXStart method of the specified document visitor.
|
void |
appendContent(Section sourceSection)
Inserts a copy of content of the source section at the end of this section.
|
void |
clearContent()
Clears the section.
|
void |
clearHeadersFooters()
Clears the headers and footers of this section.
|
void |
clearHeadersFooters(boolean preserveWatermarks)
Clears the headers and footers of this section.
|
void |
clearSectionAttrs() |
Section |
deepClone()
Creates a duplicate of this section.
|
void |
deleteHeaderFooterShapes()
Deletes all shapes (drawing objects) from the headers and footers of this section.
|
void |
ensureMinimum()
|
java.lang.Object |
fetchInheritedSectionAttr(int key) |
java.lang.Object |
fetchSectionAttr(int key) |
java.lang.Object |
fetchSectionAttr(int key,
int revisionsView) |
Body |
getBody()
Returns the
Body child node of the section. |
java.lang.Object |
getDirectSectionAttr(int key) |
java.lang.Object |
getDirectSectionAttr(int key,
int revisionsView) |
HeaderFooterCollection |
getHeadersFooters()
Provides access to the headers and footers nodes of the section.
|
int |
getNodeType()
Returns
NodeType.SECTION. |
PageSetup |
getPageSetup()
Returns an object that represents page setup and section properties.
|
boolean |
getProtectedForForms()
True if the section is protected for forms.
|
void |
prependContent(Section sourceSection)
Inserts a copy of content of the source section at the beginning of this section.
|
void |
setProtectedForForms(boolean value)
True if the section is protected for forms.
|
void |
setSectionAttr(int key,
java.lang.Object value) |
void |
setSectionAttr(int key,
java.lang.Object value,
int revisionsView) |
java.lang.String |
toString() |
acceptChildren, 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, visitorActionToBoolpublic Section(DocumentBase doc)
Remarks:
When the section is created, it belongs to the specified document, but is not yet part of the document and Node.getParentNode() is null.
To include Section into a document use CompositeNode.insertAfter(com.aspose.words.Node, com.aspose.words.Node) and CompositeNode.insertBefore(com.aspose.words.Node, com.aspose.words.Node) methods of the Document OR NodeCollection.add(com.aspose.words.Node) and NodeCollection.insert(int, com.aspose.words.Node) methods of the Document.getSections() property.
Examples:
Shows how to construct an Aspose.Words document by hand.
Document doc = new Document();
// A blank document contains one section, one body and one paragraph.
// Call the "RemoveAllChildren" method to remove all those nodes,
// and end up with a document node with no children.
doc.removeAllChildren();
// This document now has no composite child nodes that we can add content to.
// If we wish to edit it, we will need to repopulate its node collection.
// First, create a new section, and then append it as a child to the root document node.
Section section = new Section(doc);
doc.appendChild(section);
// Set some page setup properties for the section.
section.getPageSetup().setSectionStart(SectionStart.NEW_PAGE);
section.getPageSetup().setPaperSize(PaperSize.LETTER);
// A section needs a body, which will contain and display all its contents
// on the page between the section's header and footer.
Body body = new Body(doc);
section.appendChild(body);
// Create a paragraph, set some formatting properties, and then append it as a child to the body.
Paragraph para = new Paragraph(doc);
para.getParagraphFormat().setStyleName("Heading 1");
para.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
body.appendChild(para);
// Finally, add some content to do the document. Create a run,
// set its appearance and contents, and then append it as a child to the paragraph.
Run run = new Run(doc);
run.setText("Hello World!");
run.getFont().setColor(Color.RED);
para.appendChild(run);
Assert.assertEquals("Hello World!", doc.getText().trim());
doc.save(getArtifactsDir() + "Section.CreateManually.docx");
doc - The owner document.public int getNodeType()
NodeType.SECTION.
Examples:
Shows how to traverse a composite node's tree of child nodes.
public void recurseChildren() throws Exception {
Document doc = new Document(getMyDir() + "Paragraphs.docx");
// Any node that can contain child nodes, such as the document itself, is composite.
Assert.assertTrue(doc.isComposite());
// Invoke the recursive function that will go through and print all the child nodes of a composite node.
traverseAllNodes(doc, 0);
}
/// <summary>
/// Recursively traverses a node tree while printing the type of each node
/// with an indent depending on depth as well as the contents of all inline nodes.
/// </summary>
public void traverseAllNodes(CompositeNode parentNode, int depth) {
for (Node childNode = parentNode.getFirstChild(); childNode != null; childNode = childNode.getNextSibling()) {
System.out.println(MessageFormat.format("{0}{1}", String.format(" ", depth), Node.nodeTypeToString(childNode.getNodeType())));
// Recurse into the node if it is a composite node. Otherwise, print its contents if it is an inline node.
if (childNode.isComposite()) {
System.out.println();
traverseAllNodes((CompositeNode) childNode, depth + 1);
} else if (childNode instanceof Inline) {
System.out.println(MessageFormat.format(" - \"{0}\"", childNode.getText().trim()));
} else {
System.out.println();
}
}
}
getNodeType in class NodeNodeType.SECTION. The returned value is one of NodeType constants.public Body getBody()
Body child node of the section.
Remarks:
Body contains main text of the section.
Returns null if the section does not have a Body node among its children.
Examples:
Clears main text from all sections from the document leaving the sections themselves.
Document doc = new Document();
// A blank document contains one section, one body and one paragraph.
// Call the "RemoveAllChildren" method to remove all those nodes,
// and end up with a document node with no children.
doc.removeAllChildren();
// This document now has no composite child nodes that we can add content to.
// If we wish to edit it, we will need to repopulate its node collection.
// First, create a new section, and then append it as a child to the root document node.
Section section = new Section(doc);
doc.appendChild(section);
// A section needs a body, which will contain and display all its contents
// on the page between the section's header and footer.
Body body = new Body(doc);
section.appendChild(body);
// This body has no children, so we cannot add runs to it yet.
Assert.assertEquals(0, doc.getFirstSection().getBody().getChildNodes(NodeType.ANY, true).getCount());
// Call the "EnsureMinimum" to make sure that this body contains at least one empty paragraph.
body.ensureMinimum();
// Now, we can add runs to the body, and get the document to display them.
body.getFirstParagraph().appendChild(new Run(doc, "Hello world!"));
Assert.assertEquals("Hello world!", doc.getText().trim());
Body child node of the section.public HeaderFooterCollection getHeadersFooters()
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");
HeaderFooterCollection value.public PageSetup getPageSetup()
Examples:
Shows how to create a wide blue band border at the top of the first page.
Document doc = new Document();
PageSetup pageSetup = doc.getSections().get(0).getPageSetup();
pageSetup.setBorderAlwaysInFront(false);
pageSetup.setBorderDistanceFrom(PageBorderDistanceFrom.PAGE_EDGE);
pageSetup.setBorderAppliesTo(PageBorderAppliesTo.FIRST_PAGE);
Border border = pageSetup.getBorders().getByBorderType(BorderType.TOP);
border.setLineStyle(LineStyle.SINGLE);
border.setLineWidth(30.0);
border.setColor(Color.BLUE);
border.setDistanceFromText(0.0);
doc.save(getArtifactsDir() + "PageSetup.PageBorderProperties.docx");
Shows how to construct an Aspose.Words document by hand.
Document doc = new Document();
// A blank document contains one section, one body and one paragraph.
// Call the "RemoveAllChildren" method to remove all those nodes,
// and end up with a document node with no children.
doc.removeAllChildren();
// This document now has no composite child nodes that we can add content to.
// If we wish to edit it, we will need to repopulate its node collection.
// First, create a new section, and then append it as a child to the root document node.
Section section = new Section(doc);
doc.appendChild(section);
// Set some page setup properties for the section.
section.getPageSetup().setSectionStart(SectionStart.NEW_PAGE);
section.getPageSetup().setPaperSize(PaperSize.LETTER);
// A section needs a body, which will contain and display all its contents
// on the page between the section's header and footer.
Body body = new Body(doc);
section.appendChild(body);
// Create a paragraph, set some formatting properties, and then append it as a child to the body.
Paragraph para = new Paragraph(doc);
para.getParagraphFormat().setStyleName("Heading 1");
para.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
body.appendChild(para);
// Finally, add some content to do the document. Create a run,
// set its appearance and contents, and then append it as a child to the paragraph.
Run run = new Run(doc);
run.setText("Hello World!");
run.getFont().setColor(Color.RED);
para.appendChild(run);
Assert.assertEquals("Hello World!", doc.getText().trim());
doc.save(getArtifactsDir() + "Section.CreateManually.docx");
public boolean getProtectedForForms()
Examples:
Shows how to turn off protection for a section.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.writeln("Section 1. Hello world!");
builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);
builder.writeln("Section 2. Hello again!");
builder.write("Please enter text here: ");
builder.insertTextInput("TextInput1", TextFormFieldType.REGULAR, "", "Placeholder text", 0);
// Apply write protection to every section in the document.
doc.protect(ProtectionType.ALLOW_ONLY_FORM_FIELDS);
// Turn off write protection for the first section.
doc.getSections().get(0).setProtectedForForms(false);
// In this output document, we will be able to edit the first section freely,
// and we will only be able to edit the contents of the form field in the second section.
doc.save(getArtifactsDir() + "Section.Protect.docx");
boolean value.public void setProtectedForForms(boolean value)
Examples:
Shows how to turn off protection for a section.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.writeln("Section 1. Hello world!");
builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);
builder.writeln("Section 2. Hello again!");
builder.write("Please enter text here: ");
builder.insertTextInput("TextInput1", TextFormFieldType.REGULAR, "", "Placeholder text", 0);
// Apply write protection to every section in the document.
doc.protect(ProtectionType.ALLOW_ONLY_FORM_FIELDS);
// Turn off write protection for the first section.
doc.getSections().get(0).setProtectedForForms(false);
// In this output document, we will be able to edit the first section freely,
// and we will only be able to edit the contents of the form field in the second section.
doc.save(getArtifactsDir() + "Section.Protect.docx");
value - The corresponding boolean value.public Section deepClone()
Examples:
Shows how to add and remove sections in a document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.write("Section 1");
builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);
builder.write("Section 2");
Assert.assertEquals("Section 1\fSection 2", doc.getText().trim());
// Delete the first section from the document.
doc.getSections().removeAt(0);
Assert.assertEquals("Section 2", doc.getText().trim());
// Append a copy of what is now the first section to the end of the document.
int lastSectionIdx = doc.getSections().getCount() - 1;
Section newSection = doc.getSections().get(lastSectionIdx).deepClone();
doc.getSections().add(newSection);
Assert.assertEquals("Section 2\fSection 2", doc.getText().trim());
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.visitSectionStart(com.aspose.words.Section), then calls Node.accept(com.aspose.words.DocumentVisitor) for all child nodes of the section and calls DocumentVisitor.visitSectionEnd(com.aspose.words.Section) at the end.
Examples:
Shows how to use a document visitor to print a document's node structure.
public void docStructureToText() throws Exception {
Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx");
DocStructurePrinter visitor = new DocStructurePrinter();
// 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());
}
/// <summary>
/// Traverses a node's tree of child nodes.
/// Creates a map of this tree in the form of a string.
/// </summary>
public static class DocStructurePrinter extends DocumentVisitor {
public DocStructurePrinter() {
mAcceptingNodeChildTree = new StringBuilder();
}
public String getText() {
return mAcceptingNodeChildTree.toString();
}
/// <summary>
/// Called when a Document node is encountered.
/// </summary>
public int visitDocumentStart(Document doc) {
int childNodeCount = doc.getChildNodes(NodeType.ANY, true).getCount();
indentAndAppendLine("[Document start] Child nodes: " + childNodeCount);
mDocTraversalDepth++;
// Allow the visitor to continue visiting other nodes.
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called after all the child nodes of a Document node have been visited.
/// </summary>
public int visitDocumentEnd(Document doc) {
mDocTraversalDepth--;
indentAndAppendLine("[Document end]");
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called when a Section node is encountered in the document.
/// </summary>
public int visitSectionStart(final Section section) {
// Get the index of our section within the document
NodeCollection docSections = section.getDocument().getChildNodes(NodeType.SECTION, false);
int sectionIndex = docSections.indexOf(section);
indentAndAppendLine("[Section start] Section index: " + sectionIndex);
mDocTraversalDepth++;
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called after all the child nodes of a Section node have been visited.
/// </summary>
public int visitSectionEnd(final Section section) {
mDocTraversalDepth--;
indentAndAppendLine("[Section end]");
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called when a Body node is encountered in the document.
/// </summary>
public int visitBodyStart(final Body body) {
int paragraphCount = body.getParagraphs().getCount();
indentAndAppendLine("[Body start] Paragraphs: " + paragraphCount);
mDocTraversalDepth++;
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called after all the child nodes of a Body node have been visited.
/// </summary>
public int visitBodyEnd(final Body body) {
mDocTraversalDepth--;
indentAndAppendLine("[Body end]");
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called when a Paragraph node is encountered in the document.
/// </summary>
public int visitParagraphStart(final Paragraph paragraph) {
indentAndAppendLine("[Paragraph start]");
mDocTraversalDepth++;
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called after all the child nodes of a Paragraph node have been visited.
/// </summary>
public int visitParagraphEnd(final Paragraph paragraph) {
mDocTraversalDepth--;
indentAndAppendLine("[Paragraph end]");
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called when a Run node is encountered in the document.
/// </summary>
public int visitRun(final Run run) {
indentAndAppendLine("[Run] \"" + run.getText() + "\"");
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called when a SubDocument node is encountered in the document.
/// </summary>
public int visitSubDocument(final SubDocument subDocument) {
indentAndAppendLine("[SubDocument]");
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called when a SubDocument node is encountered in the document.
/// </summary>
public int visitStructuredDocumentTagRangeStart(StructuredDocumentTagRangeStart sdtRangeStart)
{
indentAndAppendLine("[SdtRangeStart]");
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called when a SubDocument node is encountered in the document.
/// </summary>
public int visitStructuredDocumentTagRangeEnd(StructuredDocumentTagRangeEnd sdtRangeEnd)
{
indentAndAppendLine("[SdtRangeEnd]");
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++) {
mAcceptingNodeChildTree.append("| ");
}
mAcceptingNodeChildTree.append(text + "\r\n");
}
private int mDocTraversalDepth;
private final StringBuilder mAcceptingNodeChildTree;
}
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
CompositeNodeExamples:
Shows how to use a document visitor to print a document's node structure.
public void docStructureToText() throws Exception {
Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx");
DocStructurePrinter visitor = new DocStructurePrinter();
// 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());
}
/// <summary>
/// Traverses a node's tree of child nodes.
/// Creates a map of this tree in the form of a string.
/// </summary>
public static class DocStructurePrinter extends DocumentVisitor {
public DocStructurePrinter() {
mAcceptingNodeChildTree = new StringBuilder();
}
public String getText() {
return mAcceptingNodeChildTree.toString();
}
/// <summary>
/// Called when a Document node is encountered.
/// </summary>
public int visitDocumentStart(Document doc) {
int childNodeCount = doc.getChildNodes(NodeType.ANY, true).getCount();
indentAndAppendLine("[Document start] Child nodes: " + childNodeCount);
mDocTraversalDepth++;
// Allow the visitor to continue visiting other nodes.
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called after all the child nodes of a Document node have been visited.
/// </summary>
public int visitDocumentEnd(Document doc) {
mDocTraversalDepth--;
indentAndAppendLine("[Document end]");
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called when a Section node is encountered in the document.
/// </summary>
public int visitSectionStart(final Section section) {
// Get the index of our section within the document
NodeCollection docSections = section.getDocument().getChildNodes(NodeType.SECTION, false);
int sectionIndex = docSections.indexOf(section);
indentAndAppendLine("[Section start] Section index: " + sectionIndex);
mDocTraversalDepth++;
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called after all the child nodes of a Section node have been visited.
/// </summary>
public int visitSectionEnd(final Section section) {
mDocTraversalDepth--;
indentAndAppendLine("[Section end]");
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called when a Body node is encountered in the document.
/// </summary>
public int visitBodyStart(final Body body) {
int paragraphCount = body.getParagraphs().getCount();
indentAndAppendLine("[Body start] Paragraphs: " + paragraphCount);
mDocTraversalDepth++;
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called after all the child nodes of a Body node have been visited.
/// </summary>
public int visitBodyEnd(final Body body) {
mDocTraversalDepth--;
indentAndAppendLine("[Body end]");
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called when a Paragraph node is encountered in the document.
/// </summary>
public int visitParagraphStart(final Paragraph paragraph) {
indentAndAppendLine("[Paragraph start]");
mDocTraversalDepth++;
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called after all the child nodes of a Paragraph node have been visited.
/// </summary>
public int visitParagraphEnd(final Paragraph paragraph) {
mDocTraversalDepth--;
indentAndAppendLine("[Paragraph end]");
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called when a Run node is encountered in the document.
/// </summary>
public int visitRun(final Run run) {
indentAndAppendLine("[Run] \"" + run.getText() + "\"");
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called when a SubDocument node is encountered in the document.
/// </summary>
public int visitSubDocument(final SubDocument subDocument) {
indentAndAppendLine("[SubDocument]");
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called when a SubDocument node is encountered in the document.
/// </summary>
public int visitStructuredDocumentTagRangeStart(StructuredDocumentTagRangeStart sdtRangeStart)
{
indentAndAppendLine("[SdtRangeStart]");
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called when a SubDocument node is encountered in the document.
/// </summary>
public int visitStructuredDocumentTagRangeEnd(StructuredDocumentTagRangeEnd sdtRangeEnd)
{
indentAndAppendLine("[SdtRangeEnd]");
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++) {
mAcceptingNodeChildTree.append("| ");
}
mAcceptingNodeChildTree.append(text + "\r\n");
}
private int mDocTraversalDepth;
private final StringBuilder mAcceptingNodeChildTree;
}
acceptStart in class CompositeNodejava.lang.Exceptionpublic int acceptEnd(DocumentVisitor visitor) throws java.lang.Exception
CompositeNodeExamples:
Shows how to use a document visitor to print a document's node structure.
public void docStructureToText() throws Exception {
Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx");
DocStructurePrinter visitor = new DocStructurePrinter();
// 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());
}
/// <summary>
/// Traverses a node's tree of child nodes.
/// Creates a map of this tree in the form of a string.
/// </summary>
public static class DocStructurePrinter extends DocumentVisitor {
public DocStructurePrinter() {
mAcceptingNodeChildTree = new StringBuilder();
}
public String getText() {
return mAcceptingNodeChildTree.toString();
}
/// <summary>
/// Called when a Document node is encountered.
/// </summary>
public int visitDocumentStart(Document doc) {
int childNodeCount = doc.getChildNodes(NodeType.ANY, true).getCount();
indentAndAppendLine("[Document start] Child nodes: " + childNodeCount);
mDocTraversalDepth++;
// Allow the visitor to continue visiting other nodes.
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called after all the child nodes of a Document node have been visited.
/// </summary>
public int visitDocumentEnd(Document doc) {
mDocTraversalDepth--;
indentAndAppendLine("[Document end]");
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called when a Section node is encountered in the document.
/// </summary>
public int visitSectionStart(final Section section) {
// Get the index of our section within the document
NodeCollection docSections = section.getDocument().getChildNodes(NodeType.SECTION, false);
int sectionIndex = docSections.indexOf(section);
indentAndAppendLine("[Section start] Section index: " + sectionIndex);
mDocTraversalDepth++;
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called after all the child nodes of a Section node have been visited.
/// </summary>
public int visitSectionEnd(final Section section) {
mDocTraversalDepth--;
indentAndAppendLine("[Section end]");
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called when a Body node is encountered in the document.
/// </summary>
public int visitBodyStart(final Body body) {
int paragraphCount = body.getParagraphs().getCount();
indentAndAppendLine("[Body start] Paragraphs: " + paragraphCount);
mDocTraversalDepth++;
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called after all the child nodes of a Body node have been visited.
/// </summary>
public int visitBodyEnd(final Body body) {
mDocTraversalDepth--;
indentAndAppendLine("[Body end]");
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called when a Paragraph node is encountered in the document.
/// </summary>
public int visitParagraphStart(final Paragraph paragraph) {
indentAndAppendLine("[Paragraph start]");
mDocTraversalDepth++;
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called after all the child nodes of a Paragraph node have been visited.
/// </summary>
public int visitParagraphEnd(final Paragraph paragraph) {
mDocTraversalDepth--;
indentAndAppendLine("[Paragraph end]");
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called when a Run node is encountered in the document.
/// </summary>
public int visitRun(final Run run) {
indentAndAppendLine("[Run] \"" + run.getText() + "\"");
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called when a SubDocument node is encountered in the document.
/// </summary>
public int visitSubDocument(final SubDocument subDocument) {
indentAndAppendLine("[SubDocument]");
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called when a SubDocument node is encountered in the document.
/// </summary>
public int visitStructuredDocumentTagRangeStart(StructuredDocumentTagRangeStart sdtRangeStart)
{
indentAndAppendLine("[SdtRangeStart]");
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called when a SubDocument node is encountered in the document.
/// </summary>
public int visitStructuredDocumentTagRangeEnd(StructuredDocumentTagRangeEnd sdtRangeEnd)
{
indentAndAppendLine("[SdtRangeEnd]");
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++) {
mAcceptingNodeChildTree.append("| ");
}
mAcceptingNodeChildTree.append(text + "\r\n");
}
private int mDocTraversalDepth;
private final StringBuilder mAcceptingNodeChildTree;
}
acceptEnd in class CompositeNodejava.lang.Exceptionpublic void prependContent(Section sourceSection)
Remarks:
Only content of getBody() of the source section is copied, page setup, headers and footers are not copied.
The nodes are automatically imported if the source section belongs to a different document.
No new section is created in the destination document.
Examples:
Shows how to append the contents of a section to another section.
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");
Section section = doc.getSections().get(2);
Assert.assertEquals("Section 3" + ControlChar.SECTION_BREAK, section.getText());
// Insert the contents of the first section to the beginning of the third section.
Section sectionToPrepend = doc.getSections().get(0);
section.prependContent(sectionToPrepend);
// Insert the contents of the second section to the end of the third section.
Section sectionToAppend = doc.getSections().get(1);
section.appendContent(sectionToAppend);
// The "PrependContent" and "AppendContent" methods did not create any new sections.
Assert.assertEquals(3, doc.getSections().getCount());
Assert.assertEquals("Section 1" + ControlChar.PARAGRAPH_BREAK +
"Section 3" + ControlChar.PARAGRAPH_BREAK +
"Section 2" + ControlChar.SECTION_BREAK, section.getText());
sourceSection - The section to copy content from.public void appendContent(Section sourceSection)
Remarks:
Only content of getBody() of the source section is copied, page setup, headers and footers are not copied.
The nodes are automatically imported if the source section belongs to a different document.
No new section is created in the destination document.
Examples:
Shows how to append the contents of a section to another section.
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");
Section section = doc.getSections().get(2);
Assert.assertEquals("Section 3" + ControlChar.SECTION_BREAK, section.getText());
// Insert the contents of the first section to the beginning of the third section.
Section sectionToPrepend = doc.getSections().get(0);
section.prependContent(sectionToPrepend);
// Insert the contents of the second section to the end of the third section.
Section sectionToAppend = doc.getSections().get(1);
section.appendContent(sectionToAppend);
// The "PrependContent" and "AppendContent" methods did not create any new sections.
Assert.assertEquals(3, doc.getSections().getCount());
Assert.assertEquals("Section 1" + ControlChar.PARAGRAPH_BREAK +
"Section 3" + ControlChar.PARAGRAPH_BREAK +
"Section 2" + ControlChar.SECTION_BREAK, section.getText());
sourceSection - The section to copy content from.public void clearContent()
Remarks:
The text of getBody() is cleared, only one empty paragraph is left that represents the section break.
The text of all headers and footers is cleared, but HeaderFooter objects themselves are not removed.
Examples:
Shows how to clear the contents of a section.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.write("Hello world!");
Assert.assertEquals("Hello world!", doc.getText().trim());
Assert.assertEquals(1, doc.getFirstSection().getBody().getParagraphs().getCount());
// Running the "ClearContent" method will remove all the section contents
// but leave a blank paragraph to add content again.
doc.getFirstSection().clearContent();
Assert.assertEquals("", doc.getText().trim());
Assert.assertEquals(1, doc.getFirstSection().getBody().getParagraphs().getCount());
public void clearHeadersFooters()
Remarks:
The text of all headers and footers is cleared, but HeaderFooter objects themselves are not removed.
This makes headers and footers of this section linked to headers and footers of the previous section.
Examples:
Shows how to clear the contents of all headers and footers in a section.
Document doc = new Document();
Assert.assertEquals(0, doc.getFirstSection().getHeadersFooters().getCount());
DocumentBuilder builder = new DocumentBuilder(doc);
builder.moveToHeaderFooter(HeaderFooterType.HEADER_PRIMARY);
builder.writeln("This is the primary header.");
builder.moveToHeaderFooter(HeaderFooterType.FOOTER_PRIMARY);
builder.writeln("This is the primary footer.");
Assert.assertEquals(2, doc.getFirstSection().getHeadersFooters().getCount());
Assert.assertEquals("This is the primary header.", doc.getFirstSection().getHeadersFooters().getByHeaderFooterType(HeaderFooterType.HEADER_PRIMARY).getText().trim());
Assert.assertEquals("This is the primary footer.", doc.getFirstSection().getHeadersFooters().getByHeaderFooterType(HeaderFooterType.FOOTER_PRIMARY).getText().trim());
// Empty all the headers and footers in this section of all their contents.
// The headers and footers themselves will still be present but will have nothing to display.
doc.getFirstSection().clearHeadersFooters();
Assert.assertEquals(2, doc.getFirstSection().getHeadersFooters().getCount());
Assert.assertEquals("", doc.getFirstSection().getHeadersFooters().getByHeaderFooterType(HeaderFooterType.HEADER_PRIMARY).getText().trim());
Assert.assertEquals("", doc.getFirstSection().getHeadersFooters().getByHeaderFooterType(HeaderFooterType.FOOTER_PRIMARY).getText().trim());
public void clearHeadersFooters(boolean preserveWatermarks)
Remarks:
The text of all headers and footers is cleared, but HeaderFooter objects themselves are not removed.
This makes headers and footers of this section linked to headers and footers of the previous section.
Examples:
Shows how to clear the contents of header and footer with or without a watermark.
Document doc = new Document(getMyDir() + "Header and footer types.docx");
// Add a plain text watermark.
doc.getWatermark().setText("Aspose Watermark");
// Make sure the headers and footers have content.
HeaderFooterCollection headersFooters = doc.getFirstSection().getHeadersFooters();
Assert.assertEquals("First header", headersFooters.getByHeaderFooterType(HeaderFooterType.HEADER_FIRST).getText().trim());
Assert.assertEquals("Second header", headersFooters.getByHeaderFooterType(HeaderFooterType.HEADER_EVEN).getText().trim());
Assert.assertEquals("Third header", headersFooters.getByHeaderFooterType(HeaderFooterType.HEADER_PRIMARY).getText().trim());
Assert.assertEquals("First footer", headersFooters.getByHeaderFooterType(HeaderFooterType.FOOTER_FIRST).getText().trim());
Assert.assertEquals("Second footer", headersFooters.getByHeaderFooterType(HeaderFooterType.FOOTER_EVEN).getText().trim());
Assert.assertEquals("Third footer", headersFooters.getByHeaderFooterType(HeaderFooterType.FOOTER_PRIMARY).getText().trim());
// Removes all header and footer content except watermarks.
doc.getFirstSection().clearHeadersFooters(true);
headersFooters = doc.getFirstSection().getHeadersFooters();
Assert.assertEquals("", headersFooters.getByHeaderFooterType(HeaderFooterType.HEADER_FIRST).getText().trim());
Assert.assertEquals("", headersFooters.getByHeaderFooterType(HeaderFooterType.HEADER_EVEN).getText().trim());
Assert.assertEquals("", headersFooters.getByHeaderFooterType(HeaderFooterType.HEADER_PRIMARY).getText().trim());
Assert.assertEquals("", headersFooters.getByHeaderFooterType(HeaderFooterType.FOOTER_FIRST).getText().trim());
Assert.assertEquals("", headersFooters.getByHeaderFooterType(HeaderFooterType.FOOTER_EVEN).getText().trim());
Assert.assertEquals("", headersFooters.getByHeaderFooterType(HeaderFooterType.FOOTER_PRIMARY).getText().trim());
Assert.assertEquals(WatermarkType.TEXT, doc.getWatermark().getType());
// Removes all header and footer content including watermarks.
doc.getFirstSection().clearHeadersFooters(false);
Assert.assertEquals(WatermarkType.NONE, doc.getWatermark().getType());
preserveWatermarks - True if the watermarks shall not be removed.public void deleteHeaderFooterShapes()
Examples:
Shows how to remove all shapes from all headers footers in a section.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Create a primary header with a shape.
builder.moveToHeaderFooter(HeaderFooterType.HEADER_PRIMARY);
builder.insertShape(ShapeType.RECTANGLE, 100.0, 100.0);
// Create a primary footer with an image.
builder.moveToHeaderFooter(HeaderFooterType.FOOTER_PRIMARY);
builder.insertImage(getImageDir() + "Logo Icon.ico");
Assert.assertEquals(1, doc.getFirstSection().getHeadersFooters().getByHeaderFooterType(HeaderFooterType.HEADER_PRIMARY).getChildNodes(NodeType.SHAPE, true).getCount());
Assert.assertEquals(1, doc.getFirstSection().getHeadersFooters().getByHeaderFooterType(HeaderFooterType.FOOTER_PRIMARY).getChildNodes(NodeType.SHAPE, true).getCount());
// Remove all shapes from the headers and footers in the first section.
doc.getFirstSection().deleteHeaderFooterShapes();
Assert.assertEquals(0, doc.getFirstSection().getHeadersFooters().getByHeaderFooterType(HeaderFooterType.HEADER_PRIMARY).getChildNodes(NodeType.SHAPE, true).getCount());
Assert.assertEquals(0, doc.getFirstSection().getHeadersFooters().getByHeaderFooterType(HeaderFooterType.FOOTER_PRIMARY).getChildNodes(NodeType.SHAPE, true).getCount());
public void ensureMinimum()
getBody() with one Paragraph.
Examples:
Shows how to prepare a new section node for editing.
Document doc = new Document();
// A blank document comes with a section, which has a body, which in turn has a paragraph.
// We can add contents to this document by adding elements such as text runs, shapes, or tables to that paragraph.
Assert.assertEquals(NodeType.SECTION, doc.getChild(NodeType.ANY, 0, true).getNodeType());
Assert.assertEquals(NodeType.BODY, doc.getSections().get(0).getChild(NodeType.ANY, 0, true).getNodeType());
Assert.assertEquals(NodeType.PARAGRAPH, doc.getSections().get(0).getBody().getChild(NodeType.ANY, 0, true).getNodeType());
// If we add a new section like this, it will not have a body, or any other child nodes.
doc.getSections().add(new Section(doc));
Assert.assertEquals(0, doc.getSections().get(1).getChildNodes(NodeType.ANY, true).getCount());
// Run the "EnsureMinimum" method to add a body and a paragraph to this section to begin editing it.
doc.getLastSection().ensureMinimum();
Assert.assertEquals(NodeType.BODY, doc.getSections().get(1).getChild(NodeType.ANY, 0, true).getNodeType());
Assert.assertEquals(NodeType.PARAGRAPH, doc.getSections().get(1).getBody().getChild(NodeType.ANY, 0, true).getNodeType());
doc.getSections().get(0).getBody().getFirstParagraph().appendChild(new Run(doc, "Hello world!"));
Assert.assertEquals("Hello world!", doc.getText().trim());
public java.lang.Object getDirectSectionAttr(int key)
public java.lang.Object getDirectSectionAttr(int key,
int revisionsView)
public java.lang.Object fetchInheritedSectionAttr(int key)
public java.lang.Object fetchSectionAttr(int key)
public java.lang.Object fetchSectionAttr(int key,
int revisionsView)
public void setSectionAttr(int key,
java.lang.Object value)
public void setSectionAttr(int key,
java.lang.Object value,
int revisionsView)
public void clearSectionAttrs()