Comments
Overview
This guide shows how to add a comment to a range of text in a Word document in Java, reply to it and mark it done, read the comments back after saving, and remove them with Aspose.Words FOSS for Java. You can attach a review comment to a stretch of text in a Word document, reply to it, mark it done, read the comments back from a saved file and remove them. A comment is a Comment node, a container for the text of the comment with an author, initials and a date. The text it refers to is marked by a CommentRangeStart node before it and a CommentRangeEnd node after it, and the Comment node itself follows the end marker. All three carry the same id. Document has no getComments method in this edition, so the comments are found with getChildNodes(NodeType.COMMENT, true). Only saving to DOCX and reloading from it was tested. The three examples were compiled and run against the published package on Java 8, 17 and 21 and printed the same output on all three.
Prerequisites
| Requirement | Detail |
|---|---|
| Java | 8 or later |
| Dependency | The package from Installation |
| Import | import com.aspose.words.*; |
| Code | The examples are statements. Put them in a method that declares throws Exception. |
Add a Comment to a Range of Text
Create the comment with its author, initials and a java.util.Date, give it an id with setId, set its text with setText, and insert the nodes in order with DocumentBuilder.insertNode: the CommentRangeStart, the text to comment on, the CommentRangeEnd and the Comment. The example saves the document and reloads it. The reloaded document had 1 comment, with the author Dana Reviewer, the initials DR and the text Please confirm this figure. Walking from the range start to the range end printed the commented text, 12%. The saved file contains word/comments.xml with one w:comment element, and word/document.xml contains the w:commentRangeStart, w:commentRangeEnd and w:commentReference elements. The example prints no date: see the time-zone note in the tips.
import com.aspose.words.*;
import java.util.Date;
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.write("Revenue grew by ");
Comment comment = new Comment(doc, "Dana Reviewer", "DR", new Date());
comment.setId(0);
comment.setText("Please confirm this figure.");
builder.insertNode(new CommentRangeStart(doc, comment.getId()));
builder.write("12%");
builder.insertNode(new CommentRangeEnd(doc, comment.getId()));
builder.insertNode(comment);
builder.write(" in the third quarter.");
doc.save("comments.docx");
Document reloaded = new Document("comments.docx");
NodeCollection comments = reloaded.getChildNodes(NodeType.COMMENT, true);
System.out.println("Comments: " + comments.getCount());
Comment saved = (Comment) comments.get(0);
System.out.println("Author: " + saved.getAuthor());
System.out.println("Initial: " + saved.getInitial());
System.out.println("Text: " + saved.getText().trim());
NodeCollection starts = reloaded.getChildNodes(NodeType.COMMENT_RANGE_START, true);
CommentRangeStart start = (CommentRangeStart) starts.get(0);
StringBuilder commented = new StringBuilder();
Node node = start.getNextSibling();
while (node != null && node.getNodeType() != NodeType.COMMENT_RANGE_END) {
commented.append(node.getText());
node = node.getNextSibling();
}
System.out.println("Commented text: " + commented);The program printed:
Comments: 1
Author: Dana Reviewer
Initial: DR
Text: Please confirm this figure.
Commented text: 12%Reply to a Comment and Mark It Done
Comment.addReply takes an author, initials, a date and the text, and returns the reply as a Comment. setDone(true) marks a comment as done. The example puts a comment on each of two ranges, adds one reply to the first and marks the first done. After saving and reloading, getChildNodes(NodeType.COMMENT, true) returned 3 comments, replies included. getAncestor() returned null for the two top-level comments, and getReplies() returned the reply of the first one. The first comment printed done: true and the second done: false. In the saved file, word/commentsExtended.xml holds a w15:done attribute for each comment and a w15:paraIdParent attribute on the reply.
import com.aspose.words.*;
import java.util.Date;
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
String[] authors = {"Dana Reviewer", "Sam Editor"};
String[] initials = {"DR", "SE"};
String[] targets = {"12%", "third quarter"};
String[] notes = {"Please confirm this figure.", "Which year is meant?"};
builder.write("Revenue grew by ");
for (int k = 0; k < 2; k++) {
Comment comment = new Comment(doc, authors[k], initials[k], new Date());
comment.setId(k);
comment.setText(notes[k]);
builder.insertNode(new CommentRangeStart(doc, k));
builder.write(targets[k]);
builder.insertNode(new CommentRangeEnd(doc, k));
builder.insertNode(comment);
builder.write(k == 0 ? " in the " : ".");
}
Comment first = (Comment) doc.getChildNodes(NodeType.COMMENT, true).get(0);
first.addReply("Alex Author", "AA", new Date(), "Confirmed against the ledger.");
first.setDone(true);
doc.save("thread.docx");
Document reloaded = new Document("thread.docx");
NodeCollection all = reloaded.getChildNodes(NodeType.COMMENT, true);
System.out.println("All comments, replies included: " + all.getCount());
for (int i = 0; i < all.getCount(); i++) {
Comment comment = (Comment) all.get(i);
if (comment.getAncestor() != null) {
continue;
}
System.out.println(comment.getAuthor() + ": " + comment.getText().trim() + " (done: " + comment.getDone() + ")");
CommentCollection replies = comment.getReplies();
for (int j = 0; j < replies.getCount(); j++) {
Comment reply = replies.get(j);
System.out.println(" reply from " + reply.getAuthor() + ": " + reply.getText().trim());
}
}The program printed:
All comments, replies included: 3
Dana Reviewer: Please confirm this figure. (done: true)
reply from Alex Author: Confirmed against the ledger.
Sam Editor: Which year is meant? (done: false)Remove the Comments of One Reviewer
The example builds three comments by two reviewers, adds a reply to the second, saves and reloads the document and then removes the comments of Sam Editor. For each of them it calls removeAllReplies, removes the CommentRangeStart and CommentRangeEnd nodes that have the same id, and removes the comment with remove. The document went from 4 comments and 4 range starts to 2 comments and 2 range starts, and the two comments left were the ones by Dana Reviewer. In a test, Comment.remove on its own removed only the Comment node: the document still held its range start and end nodes, and a reply to the removed comment stayed in the document. removeAllReplies and removeReply removed the reply together with its range markers.
import com.aspose.words.*;
import java.util.ArrayList;
import java.util.Date;
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
String[] authors = {"Dana Reviewer", "Sam Editor", "Dana Reviewer"};
for (int k = 0; k < 3; k++) {
Comment comment = new Comment(doc, authors[k], "XX", new Date());
comment.setId(k);
comment.setText("Note " + k);
builder.insertNode(new CommentRangeStart(doc, k));
builder.write("Part " + k);
builder.insertNode(new CommentRangeEnd(doc, k));
builder.insertNode(comment);
builder.write(". ");
}
Comment sams = (Comment) doc.getChildNodes(NodeType.COMMENT, true).get(1);
sams.addReply("Alex Author", "AA", new Date(), "Agreed.");
doc.save("review.docx");
Document reloaded = new Document("review.docx");
System.out.println("Before: " + reloaded.getChildNodes(NodeType.COMMENT, true).getCount() + " comments, "
+ reloaded.getChildNodes(NodeType.COMMENT_RANGE_START, true).getCount() + " range starts");
ArrayList<Comment> doomed = new ArrayList<Comment>();
NodeCollection all = reloaded.getChildNodes(NodeType.COMMENT, true);
for (int i = 0; i < all.getCount(); i++) {
Comment comment = (Comment) all.get(i);
if (comment.getAncestor() == null && "Sam Editor".equals(comment.getAuthor())) {
doomed.add(comment);
}
}
for (Comment comment : doomed) {
int id = comment.getId();
comment.removeAllReplies();
NodeCollection starts = reloaded.getChildNodes(NodeType.COMMENT_RANGE_START, true);
for (int i = starts.getCount() - 1; i >= 0; i--) {
if (((CommentRangeStart) starts.get(i)).getId() == id) {
starts.get(i).remove();
}
}
NodeCollection ends = reloaded.getChildNodes(NodeType.COMMENT_RANGE_END, true);
for (int i = ends.getCount() - 1; i >= 0; i--) {
if (((CommentRangeEnd) ends.get(i)).getId() == id) {
ends.get(i).remove();
}
}
comment.remove();
}
reloaded.save("cleaned.docx");
Document cleaned = new Document("cleaned.docx");
NodeCollection left = cleaned.getChildNodes(NodeType.COMMENT, true);
System.out.println("After: " + left.getCount() + " comments, "
+ cleaned.getChildNodes(NodeType.COMMENT_RANGE_START, true).getCount() + " range starts");
for (int i = 0; i < left.getCount(); i++) {
Comment comment = (Comment) left.get(i);
System.out.println(comment.getAuthor() + ": " + comment.getText().trim());
}The program printed:
Before: 4 comments, 4 range starts
After: 2 comments, 2 range starts
Dana Reviewer: Note 0
Dana Reviewer: Note 2Tips and Best Practices
- Give the
CommentRangeStart, theCommentRangeEndand theCommentthe same id. In a test where the end marker had a different id from the comment, the saved file contained the comment and itsw:commentReference, but now:commentRangeStartorw:commentRangeEnd. - Copy the comment nodes into an
ArrayListbefore you remove any of them, as the last example does. The collection thatgetChildNodesreturns follows the document: in a test its count dropped from 3 to 2 after one comment was removed, and a forward index loop that removed every comment of 3 visited 2 of them and left 1. Loop backwards, as the example does for the range markers, or work from a copy. - Check the date with a fixed time zone if other tools read the file. In a test on Java 8, 17 and 21 the instant 2023-11-14T22:13:20Z was written to the
w:dateattribute ofword/comments.xmlas 2023-11-14T22:13:20Z under-Duser.timezone=UTC, as 2023-11-14T17:13:20Z under America/New_York and as 2023-11-15T03:13:20Z under Asia/Karachi, so the written value followed the JVM time zone. Reloaded through the library,getDateTimereturned the same instant in all three zones.
Common Issues
| Issue | Cause | Fix |
|---|---|---|
| The compiler reports cannot find symbol for Document. | The com.aspose.words package is not imported. | Add import com.aspose.words.*;. |
| The compiler reports an unreported exception. | The Document constructors, Document.save and some other methods declare throws Exception. | Declare it on the calling method or catch it. |
The compiler reports cannot find symbol for getComments on Document. | Document has no getComments method in this edition (checked with javap). | Use doc.getChildNodes(NodeType.COMMENT, true). |
Document.getText returns the text of the comments mixed into the body text. | In a test, getText of the document and of a paragraph contained the comment text after the commented text (Revenue grew by 12% and then Please confirm this figure.), with control characters around it (U+0005 before the comment text, a carriage return after it and a form feed at the end), so the comment text is part of the returned string. | Remove the comments if you need the body text on its own; after the comments were removed in a test, the text no longer contained them. |
| The comment is in the saved file but has no commented range. | The range markers did not have the id of the comment. | Create CommentRangeStart and CommentRangeEnd with the id that Comment.getId returns after setId. |
Range start and end nodes are left in the document after Comment.remove. | remove removes only the Comment node; the markers stay in the in-memory document, and in a test the orphaned markers were dropped when the document was saved and reloaded. | Remove the CommentRangeStart and CommentRangeEnd nodes with the same id too, as in the last example. |
FAQ
How do I list the comments of a document?
Call getChildNodes(NodeType.COMMENT, true) on the document and read the result with an index loop. Replies are in that list too; getAncestor() returns null for a top-level comment.
How do I read the text a comment refers to?
Start at the CommentRangeStart node and follow getNextSibling() until the CommentRangeEnd node. The first example printed 12% this way.
Can a comment have replies?
Yes. addReply adds one, getReplies returns the replies of a comment and removeReply or removeAllReplies removes them. The second example read one reply back after a save and reload.
Which formats were tested?
Only DOCX: the examples save a DOCX file and reload it.
API Reference Summary
| Class / Method | Description |
|---|---|
Comment | Represents a container for text of a comment. |
CommentRangeStart | Denotes the start of a region of text that has a comment associated with it. |
CommentRangeEnd | Denotes the end of a region of text that has a comment associated with it. |
CommentCollection | Provides typed access to a collection of Comment nodes. |
Comment.setText(text) | This is a convenience method that allows to easily set text of the comment. |
Comment.getAuthor() | Returns or sets the author name for a comment. |
Comment.getInitial() | Returns or sets the initials of the user associated with a specific comment. |
Comment.getReplies() | Returns a collection of Comment objects that are immediate children of the specified comment. |
Comment.getDone() | Gets or sets flag indicating that the comment has been marked done. |
Comment.removeAllReplies() | Removes all replies to this comment. |
DocumentBuilder.insertNode(node) | Inserts a node before the cursor. |
Related Guides
- Tracked Changes
- Working with Text
- Bookmarks
- How to Add and Remove Comments in a Word Document in Java (knowledge base)