com.aspose.words

Class RunCollection

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

Provides typed access to a collection of Run nodes.

Example:

Shows how to determine the revision type of an inline node.
Document doc = new Document(getMyDir() + "Revision runs.docx");

// When we edit the document while the "Track Changes" option, found in via Review -> Tracking,
// is turned on in Microsoft Word, the changes we apply count as revisions.
// When editing a document using Aspose.Words, we can begin tracking revisions by
// invoking the document's "StartTrackRevisions" method and stop tracking by using the "StopTrackRevisions" method.
// We can either accept revisions to assimilate them into the document
// or reject them to change the proposed change effectively.
Assert.assertEquals(6, doc.getRevisions().getCount());

// The parent node of a revision is the run that the revision concerns. A Run is an Inline node.
Run run = (Run) doc.getRevisions().get(0).getParentNode();

Paragraph firstParagraph = run.getParentParagraph();
RunCollection runs = firstParagraph.getRuns();

Assert.assertEquals(runs.getCount(), 6);

// Below are five types of revisions that can flag an Inline node.
// 1 -  An "insert" revision:
// This revision occurs when we insert text while tracking changes.
Assert.assertTrue(runs.get(2).isInsertRevision());

// 2 -  A "format" revision:
// This revision occurs when we change the formatting of text while tracking changes.
Assert.assertTrue(runs.get(2).isFormatRevision());

// 3 -  A "move from" revision:
// When we highlight text in Microsoft Word, and then drag it to a different place in the document
// while tracking changes, two revisions appear.
// The "move from" revision is a copy of the text originally before we moved it.
Assert.assertTrue(runs.get(4).isMoveFromRevision());

// 4 -  A "move to" revision:
// The "move to" revision is the text that we moved in its new position in the document.
// "Move from" and "move to" revisions appear in pairs for every move revision we carry out.
// Accepting a move revision deletes the "move from" revision and its text,
// and keeps the text from the "move to" revision.
// Rejecting a move revision conversely keeps the "move from" revision and deletes the "move to" revision.
Assert.assertTrue(runs.get(1).isMoveToRevision());

// 5 -  A "delete" revision:
// This revision occurs when we delete text while tracking changes. When we delete text like this,
// it will stay in the document as a revision until we either accept the revision,
// which will delete the text for good, or reject the revision, which will keep the text we deleted where it was.
Assert.assertTrue(runs.get(5).isDeleteRevision());

Property Getters/Setters Summary
intgetCount()
Gets the number of nodes in the collection.
Runget(int index)
Retrieves a Run at the given index.
 
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()
Provides a simple "foreach" style iteration over the collection of nodes.
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.
Run[]toArray()
Copies all runs from the collection to a new array of runs.
 

    • Property Getters/Setters Detail

      • getCount

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

        Example:

        Shows how to traverse through a composite node's collection of child nodes.
        Document doc = new Document();
        
        // Add two runs and one shape as child nodes to the first paragraph of this document.
        Paragraph paragraph = (Paragraph) doc.getChild(NodeType.PARAGRAPH, 0, true);
        paragraph.appendChild(new Run(doc, "Hello world! "));
        
        Shape shape = new Shape(doc, ShapeType.RECTANGLE);
        shape.setWidth(200.0);
        shape.setHeight(200.0);
        // Note that the 'CustomNodeId' is not saved to an output file and exists only during the node lifetime.
        shape.setCustomNodeId(100);
        shape.setWrapType(WrapType.INLINE);
        paragraph.appendChild(shape);
        
        paragraph.appendChild(new Run(doc, "Hello again!"));
        
        // Iterate through the paragraph's collection of immediate children,
        // and print any runs or shapes that we find within.
        NodeCollection children = paragraph.getChildNodes();
        
        Assert.assertEquals(3, paragraph.getChildNodes().getCount());
        
        for (Node child : (Iterable<Node>) children)
            switch (child.getNodeType()) {
                case NodeType.RUN:
                    System.out.println("Run contents:");
                    System.out.println("\t\"{child.GetText().Trim()}\"");
                    break;
                case NodeType.SHAPE:
                    Shape childShape = (Shape) child;
                    System.out.println("Shape:");
                    System.out.println("\t{childShape.ShapeType}, {childShape.Width}x{childShape.Height}");
                    break;
            }

        Example:

        Shows how to find out if a tables are nested.
        public void calculateDepthOfNestedTables() throws Exception {
            Document doc = new Document(getMyDir() + "Nested tables.docx");
            NodeCollection tables = doc.getChildNodes(NodeType.TABLE, true);
        
            for (int i = 0; i < tables.getCount(); i++) {
                Table table = (Table) tables.get(i);
        
                // Find out if any cells in the table have other tables as children.
                int count = getChildTableCount(table);
                System.out.print(MessageFormat.format("Table #{0} has {1} tables directly within its cells", i, count));
        
                // Find out if the table is nested inside another table, and, if so, 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}", i, tableDepth));
                else
                    System.out.println(MessageFormat.format("Table #{0} is a non nested table (is not a child of another table)", i));
            }
        }
        
        /**
         * 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;
            Node parent = table.getAncestor(table.getNodeType());
        
            while (parent != null) {
                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 childTableCount = 0;
        
            for (Row row : table.getRows()) {
                for (Cell cell : row.getCells()) {
                    TableCollection childTables = cell.getTables();
        
                    if (childTables.getCount() > 0) childTableCount++;
                }
            }
        
            return childTableCount;
        }
      • get

        public Run get(int index)
        
        Retrieves a Run 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 determine the revision type of an inline node.
        Document doc = new Document(getMyDir() + "Revision runs.docx");
        
        // When we edit the document while the "Track Changes" option, found in via Review -> Tracking,
        // is turned on in Microsoft Word, the changes we apply count as revisions.
        // When editing a document using Aspose.Words, we can begin tracking revisions by
        // invoking the document's "StartTrackRevisions" method and stop tracking by using the "StopTrackRevisions" method.
        // We can either accept revisions to assimilate them into the document
        // or reject them to change the proposed change effectively.
        Assert.assertEquals(6, doc.getRevisions().getCount());
        
        // The parent node of a revision is the run that the revision concerns. A Run is an Inline node.
        Run run = (Run) doc.getRevisions().get(0).getParentNode();
        
        Paragraph firstParagraph = run.getParentParagraph();
        RunCollection runs = firstParagraph.getRuns();
        
        Assert.assertEquals(runs.getCount(), 6);
        
        // Below are five types of revisions that can flag an Inline node.
        // 1 -  An "insert" revision:
        // This revision occurs when we insert text while tracking changes.
        Assert.assertTrue(runs.get(2).isInsertRevision());
        
        // 2 -  A "format" revision:
        // This revision occurs when we change the formatting of text while tracking changes.
        Assert.assertTrue(runs.get(2).isFormatRevision());
        
        // 3 -  A "move from" revision:
        // When we highlight text in Microsoft Word, and then drag it to a different place in the document
        // while tracking changes, two revisions appear.
        // The "move from" revision is a copy of the text originally before we moved it.
        Assert.assertTrue(runs.get(4).isMoveFromRevision());
        
        // 4 -  A "move to" revision:
        // The "move to" revision is the text that we moved in its new position in the document.
        // "Move from" and "move to" revisions appear in pairs for every move revision we carry out.
        // Accepting a move revision deletes the "move from" revision and its text,
        // and keeps the text from the "move to" revision.
        // Rejecting a move revision conversely keeps the "move from" revision and deletes the "move to" revision.
        Assert.assertTrue(runs.get(1).isMoveToRevision());
        
        // 5 -  A "delete" revision:
        // This revision occurs when we delete text while tracking changes. When we delete text like this,
        // it will stay in the document as a revision until we either accept the revision,
        // which will delete the text for good, or reject the revision, which will keep the text we deleted where it was.
        Assert.assertTrue(runs.get(5).isDeleteRevision());
    • 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 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());
      • 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.docx");
        
        // This document has one section with a few child nodes containing and displaying all the document's contents.
        Assert.assertEquals(1, doc.getSections().getCount());
        Assert.assertEquals(19, doc.getSections().get(0).getChildNodes(NodeType.ANY, true).getCount());
        Assert.assertEquals("Hello World!\r\rHello Word!\r\r\rHello World!", doc.getText().trim());
        
        // Clear the collection of sections, which will remove all of the document's children.
        doc.getSections().clear();
        
        Assert.assertEquals(0, doc.getChildNodes(NodeType.ANY, true).getCount());
        Assert.assertEquals("", doc.getText().trim());
      • 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);
        
        // Add text to the document by inserting Runs using a DocumentBuilder.
        builder.write("Run 1. ");
        builder.write("Run 2. ");
        
        // Every invocation of the "Write()" method creates a new Run,
        // which then appears in the parent Paragraph's RunCollection.
        RunCollection runs = doc.getFirstSection().getBody().getFirstParagraph().getRuns();
        
        Assert.assertEquals(2, runs.getCount());
        
        // We can also insert a node into the RunCollection manually.
        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());
        
        // Access individual runs and remove them to remove their text from the document.
        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:

        Shows how to get the index of a node in a collection.
        Document doc = new Document(getMyDir() + "Tables.docx");
        
        Table table = doc.getFirstSection().getBody().getTables().get(0);
        NodeCollection allTables = doc.getChildNodes(NodeType.TABLE, true);
        
        Assert.assertEquals(0, allTables.indexOf(table));
        
        Row row = table.getRows().get(2);
        
        Assert.assertEquals(2, table.indexOf(row));
        
        Cell cell = row.getLastCell();
        
        Assert.assertEquals(4, row.indexOf(cell));
      • 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);
        
        // Add text to the document by inserting Runs using a DocumentBuilder.
        builder.write("Run 1. ");
        builder.write("Run 2. ");
        
        // Every invocation of the "Write()" method creates a new Run,
        // which then appears in the parent Paragraph's RunCollection.
        RunCollection runs = doc.getFirstSection().getBody().getFirstParagraph().getRuns();
        
        Assert.assertEquals(2, runs.getCount());
        
        // We can also insert a node into the RunCollection manually.
        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());
        
        // Access individual runs and remove them to remove their text from the document.
        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()
        Provides a simple "foreach" style iteration over the collection of nodes.
        Returns:
        An Iterator.
      • 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);
        
        // Add text to the document by inserting Runs using a DocumentBuilder.
        builder.write("Run 1. ");
        builder.write("Run 2. ");
        
        // Every invocation of the "Write()" method creates a new Run,
        // which then appears in the parent Paragraph's RunCollection.
        RunCollection runs = doc.getFirstSection().getBody().getFirstParagraph().getRuns();
        
        Assert.assertEquals(2, runs.getCount());
        
        // We can also insert a node into the RunCollection manually.
        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());
        
        // Access individual runs and remove them to remove their text from the document.
        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 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());
      • toArray

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

        Example:

        Shows how to determine the revision type of an inline node.
        Document doc = new Document(getMyDir() + "Revision runs.docx");
        
        // When we edit the document while the "Track Changes" option, found in via Review -> Tracking,
        // is turned on in Microsoft Word, the changes we apply count as revisions.
        // When editing a document using Aspose.Words, we can begin tracking revisions by
        // invoking the document's "StartTrackRevisions" method and stop tracking by using the "StopTrackRevisions" method.
        // We can either accept revisions to assimilate them into the document
        // or reject them to change the proposed change effectively.
        Assert.assertEquals(6, doc.getRevisions().getCount());
        
        // The parent node of a revision is the run that the revision concerns. A Run is an Inline node.
        Run run = (Run) doc.getRevisions().get(0).getParentNode();
        
        Paragraph firstParagraph = run.getParentParagraph();
        RunCollection runs = firstParagraph.getRuns();
        
        Assert.assertEquals(runs.getCount(), 6);
        
        // Below are five types of revisions that can flag an Inline node.
        // 1 -  An "insert" revision:
        // This revision occurs when we insert text while tracking changes.
        Assert.assertTrue(runs.get(2).isInsertRevision());
        
        // 2 -  A "format" revision:
        // This revision occurs when we change the formatting of text while tracking changes.
        Assert.assertTrue(runs.get(2).isFormatRevision());
        
        // 3 -  A "move from" revision:
        // When we highlight text in Microsoft Word, and then drag it to a different place in the document
        // while tracking changes, two revisions appear.
        // The "move from" revision is a copy of the text originally before we moved it.
        Assert.assertTrue(runs.get(4).isMoveFromRevision());
        
        // 4 -  A "move to" revision:
        // The "move to" revision is the text that we moved in its new position in the document.
        // "Move from" and "move to" revisions appear in pairs for every move revision we carry out.
        // Accepting a move revision deletes the "move from" revision and its text,
        // and keeps the text from the "move to" revision.
        // Rejecting a move revision conversely keeps the "move from" revision and deletes the "move to" revision.
        Assert.assertTrue(runs.get(1).isMoveToRevision());
        
        // 5 -  A "delete" revision:
        // This revision occurs when we delete text while tracking changes. When we delete text like this,
        // it will stay in the document as a revision until we either accept the revision,
        // which will delete the text for good, or reject the revision, which will keep the text we deleted where it was.
        Assert.assertTrue(runs.get(5).isDeleteRevision());