com.aspose.words

Class CommentCollection

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

Provides typed access to a collection of Comment nodes.

Example:

Shows how to mark a comment as "done".
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.writeln("Helo world!");

// Insert a comment to point out an error. 
Comment comment = new Comment(doc, "John Doe", "J.D.", new Date());
comment.setText("Fix the spelling error!");
doc.getFirstSection().getBody().getFirstParagraph().appendChild(comment);

// Comments have a "Done" flag, which by default, is false. 
// If a comment suggests that a we make a change within the document,
// we can apply the change, and then also use that flag to indicate the correction.
Assert.assertFalse(comment.getDone());

doc.getFirstSection().getBody().getFirstParagraph().getRuns().get(0).setText("Hello world!");
comment.setDone(true);

// Comments that are "done" will differentiate themselves
// from ones that are not "done" with a faded text color.
comment = new Comment(doc, "John Doe", "J.D.", new Date());
comment.setText("Add text to this paragraph.");
builder.getCurrentParagraph().appendChild(comment);

doc.save(getArtifactsDir() + "Comment.Done.docx");

Property Getters/Setters Summary
intgetCount()
Gets the number of nodes in the collection.
Commentget(int index)
Retrieves a Comment 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.
Node[]toArray()
Copies all nodes from the collection to a new array of nodes.
 

    • Property Getters/Setters Detail

      • getCount

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

        Example:

        Shows how to enumerate immediate children of a CompositeNode using indexed access.
        Document doc = new Document();
        Paragraph paragraph = (Paragraph) doc.getChild(NodeType.PARAGRAPH, 0, true);
        paragraph.appendChild(new Run(doc, "Hello world!"));
        
        NodeCollection children = paragraph.getChildNodes();
        
        for (int i = 0; i < children.getCount(); i++) {
            Node child = children.get(i);
        
            // Paragraph may contain children of various types such as runs, shapes and so on
            if (((child.getNodeType()) == (NodeType.RUN))) {
                Run run = (Run) child;
                System.out.println(run.getText());
            }
        }

        Example:

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

        public Comment get(int index)
        
        Retrieves a Comment 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 remove comment replies.
        Document doc = new Document();
        
        Comment comment = new Comment(doc, "John Doe", "J.D.", new Date());
        comment.setText("My comment.");
        
        doc.getFirstSection().getBody().getFirstParagraph().appendChild(comment);
        
        comment.addReply("Joe Bloggs", "J.B.", new Date(), "New reply");
        comment.addReply("Joe Bloggs", "J.B.", new Date(), "Another reply");
        
        Assert.assertEquals(2, comment.getReplies().getCount());
        
        // We can remove replies from a comment individually.
        comment.removeReply(comment.getReplies().get(0));
        
        Assert.assertEquals(1, comment.getReplies().getCount());
        
        // We can also remove all of a comment's replies at once with this method.
        comment.removeAllReplies();
        
        Assert.assertEquals(0, comment.getReplies().getCount());
    • 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,
        // so we can edit the document by adding children to the paragraph like shapes or runs of text
        Assert.assertEquals(2, doc.getSections().get(0).getChildNodes(NodeType.ANY, true).getCount());
        
        // If we add a new section like this, it will not have a body or a paragraph that we can edit
        doc.getSections().add(new Section(doc));
        
        Assert.assertEquals(0, doc.getSections().get(1).getChildNodes(NodeType.ANY, true).getCount());
        
        // Makes sure that the section contains a body with at least one paragraph
        doc.getLastSection().ensureMinimum();
        
        // Now we can add content to this section
        Assert.assertEquals(2, doc.getSections().get(1).getChildNodes(NodeType.ANY, true).getCount());
      • 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");
        
        // All of the document's content is stored in the child nodes of sections like this one
        Assert.assertEquals("Hello World!", doc.getFirstSection().getBody().getText().trim());
        Assert.assertEquals(19, doc.getSections().get(0).getChildNodes(NodeType.ANY, true).getCount());
        
        doc.getSections().clear();
        
        // Clearing the section collection effectively empties the document
        Assert.assertEquals("", doc.getText());
        Assert.assertEquals(0, doc.getSections().getCount());
      • contains

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

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

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

        Example:

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

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

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

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

        Example:

        Shows how to get the indexes of nodes in the collections that contain them.
        Document doc = new Document(getMyDir() + "Tables.docx");
        
        Table table = (Table) doc.getChild(NodeType.TABLE, 0, true);
        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);
        
        // The normal way to insert Runs into a document is to add text using a DocumentBuilder
        builder.write("Run 1. ");
        builder.write("Run 2. ");
        
        // Every .Write() invocation creates a new Run, which is added to the parent Paragraph's RunCollection
        RunCollection runs = doc.getFirstSection().getBody().getFirstParagraph().getRuns();
        Assert.assertEquals(runs.getCount(), 2);
        
        // We can insert a node into the RunCollection manually to achieve the same effect
        Run newRun = new Run(doc, "Run 3. ");
        runs.insert(3, newRun);
        
        Assert.assertTrue(runs.contains(newRun));
        Assert.assertEquals("Run 1. Run 2. Run 3.", doc.getText().trim());
        
        // Text can also be deleted from the document by accessing individual Runs via the RunCollection and editing or removing them
        Run run = runs.get(1);
        runs.remove(run);
        Assert.assertEquals("Run 1. Run 3.", doc.getText().trim());
        
        Assert.assertNotNull(run);
        Assert.assertFalse(runs.contains(run));
      • iterator

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

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

        Example:

        Shows how to add/remove sections in a document.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        builder.write("Section 1");
        builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);
        builder.write("Section 2");
        
        // This shows what is in the document originally. The document has two sections
        Assert.assertEquals("Section 1\fSection 2", doc.getText().trim());
        
        // Delete the first section from the document
        doc.getSections().removeAt(0);
        
        // Duplicate the last section and append the copy to the end of the document
        int lastSectionIdx = doc.getSections().getCount() - 1;
        Section newSection = doc.getSections().get(lastSectionIdx).deepClone();
        doc.getSections().add(newSection);
        
        // Check what the document contains after we changed it
        Assert.assertEquals("Section 2\fSection 2", doc.getText().trim());
      • toArray

        public Node[] toArray()
        Copies all nodes from the collection to a new array of nodes.

        You should not be adding/removing nodes while iterating over a collection of nodes because it invalidates the iterator and requires refreshes for live collections.

        To be able to add/remove nodes during iteration, use this method to copy nodes into a fixed-size array and then iterate over the array.

        Returns:
        An array of nodes.

        Example:

        Shows how to replace all textboxes with images.
        Document doc = new Document(getMyDir() + "Textboxes in drawing canvas.docx");
        
        // This gets a live collection of all shape nodes in the document
        NodeCollection shapeCollection = doc.getChildNodes(NodeType.SHAPE, true);
        
        // Since we will be adding/removing nodes, it is better to copy all collection
        // into a fixed size array, otherwise iterator will be invalidated
        Node[] shapes = shapeCollection.toArray();
        
        for (Node node : shapes) {
            Shape shape = (Shape) node;
            // Filter out all shapes that we don't need
            if (shape.getShapeType() == ShapeType.TEXT_BOX) {
                // Create a new shape that will replace the existing shape
                Shape image = new Shape(doc, ShapeType.IMAGE);
        
                // Load the image into the new shape
                image.getImageData().setImage(getImageDir() + "Windows MetaFile.wmf");
        
                // Make new shape's position to match the old shape
                image.setLeft(shape.getLeft());
                image.setTop(shape.getTop());
                image.setWidth(shape.getWidth());
                image.setHeight(shape.getHeight());
                image.setRelativeHorizontalPosition(shape.getRelativeHorizontalPosition());
                image.setRelativeVerticalPosition(shape.getRelativeVerticalPosition());
                image.setHorizontalAlignment(shape.getHorizontalAlignment());
                image.setVerticalAlignment(shape.getVerticalAlignment());
                image.setWrapType(shape.getWrapType());
                image.setWrapSide(shape.getWrapSide());
        
                // Insert new shape after the old shape and remove the old shape
                shape.getParentNode().insertAfter(image, shape);
                shape.remove();
            }
        }
        
        doc.save(getArtifactsDir() + "Shape.ReplaceTextboxesWithImages.docx");