How to Add and Remove Comments in a Word Document in Java
Aspose.Words FOSS for Java adds a comment to a range of text in a Word document with the Comment, CommentRangeStart and CommentRangeEnd nodes. This guide adds a comment, reads it back from the saved file and removes it again, with the library from Maven Central.
Step-by-Step Guide
Step 1: Install the Package
Add the package to your build. The library needs Java 8 or later.
<dependency>
<groupId>org.aspose</groupId>
<artifactId>aspose-words-foss</artifactId>
<version>26.3.0</version>
</dependency>Step 2: Import the Classes
All classes are in the com.aspose.words package, so the example starts with import com.aspose.words.*;.
Step 3: Create the Comment and Its Range
Create a Comment with an author, initials and a java.util.Date, call setId and setText, then insert a CommentRangeStart, the text, a CommentRangeEnd and the Comment with DocumentBuilder.insertNode. All three nodes use the same id.
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%Step 4: Read the Comments Back
Save the document, reload it and call getChildNodes(NodeType.COMMENT, true). The run found 1 comment by Dana Reviewer with the initials DR, and the text between the range start and the range end was 12%. Document has no getComments method in this edition.
Step 5: Reply to a Comment
comment.addReply(author, initial, date, text) adds a reply and setDone(true) marks the comment done. After a save and reload the reply was returned by getReplies() of its parent and getAncestor() returned null for top-level comments.
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)Step 6: Remove a Comment
Call removeAllReplies, remove the CommentRangeStart and CommentRangeEnd nodes with the same id, then call remove on the comment. In a test, remove alone left the range markers in the document.
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 2Common Issues and Fixes
The compiler reports cannot find symbol for getComments. Document has no getComments method in this edition. Use getChildNodes(NodeType.COMMENT, true).
The comment is saved but has no commented range. The range markers did not have the comment’s id. In a test where the end marker had another id, the saved file had the comment and its reference but no range start or end.
Range markers are left after I removed a comment. Comment.remove removes only the Comment node. Remove the CommentRangeStart and CommentRangeEnd nodes with the same id as well.
The date in the file is off by the time zone offset. In a test on Java 8, 17 and 21 the w:date attribute written for one instant was 22:13:20Z under UTC, 17:13:20Z under America/New_York and 03:13:20Z the next day under Asia/Karachi. Run with -Duser.timezone=UTC if other tools read the date.
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.
Frequently Asked Questions
Do replies show up in the list of comments?
Yes. getChildNodes(NodeType.COMMENT, true) returned 3 comments for 2 comments and 1 reply in the example.
Does Document.getText include the comment text?
In a test it did: the comment text followed the commented text in the string that getText returned.