Working with Comments
How to Extract or Remove Comments
Using Comments in a Word document (in addition to Track Changes) is a common practice when reviewing documents, particularly when there are multiple reviewers. There can be situations where the only thing you need from a document is the comments. Say you want to generate a list of review findings, or perhaps you have collected all the useful information from the document and you simply want to remove unnecessary comments. You may want to view or remove the comments of a particular reviewer.
In this sample, we are going to look at some simple methods for both gathering information from the comments within a document and for removing comments from a document. Specifically, we’ll cover how to:
- Extract all the comments from a document or only the ones made by a particular author.
- Remove all the comments from a document or only from a particular author.
Solution
To illustrate how to extract and remove comments from a document, we will go through the following steps:
- Open a Word document using the Document class.
- Get all comments from the document into a collection.
- To extract comments:
- Go through the collection using the foreach operator.
- Extract and list the author name, date & time and text of all comments.
- Extract and list the author name, date & time and text of comments written by a specific author, in this case, the author ‘ks’.
- To remove comments:
- Go backwards through the collection using the for the operator.
- Remove comments.
- Save the changes.
The Code
The code in this sample is actually quite simple and all methods are based on the same approach. A comment in a Word document is represented by a Comment object in the Aspose.Words document object model. To collect all the comments in a document using the Document.GetChildNodes method with the first parameter set to NodeType.Comment. Make sure that the second parameter of the Document.GetChildNodes method is set to true: this forces the Document.GetChildNodes to select from all child nodes recursively, rather than only collecting the immediate children.
The Document.GetChildNodes method is very useful and you can use it every time you need to get a list of document nodes of any type. The resulting collection does not create an immediate overhead because the nodes are selected into this collection only when you enumerate or access items in it. The code example given below extracts the author’s name, date&time and text of all comments in the document.
For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C | |
std::vector<System::String> ExtractComments(const System::SharedPtr<Document>& doc) | |
{ | |
std::vector<System::String> collectedComments; | |
// Collect all comments in the document | |
System::SharedPtr<NodeCollection> comments = doc->GetChildNodes(NodeType::Comment, true); | |
// Look through all comments and gather information about them. | |
for (System::SharedPtr<Comment> comment : System::IterateOver<System::SharedPtr<Comment>>(comments)) | |
{ | |
collectedComments.push_back(comment->get_Author() + u" " + comment->get_DateTime() + u" " + System::StaticCast<Node>(comment)->ToString(SaveFormat::Text)); | |
} | |
return collectedComments; | |
} |
After you have selected Comment nodes into a collection, all you have to do is extract the information you need. In this sample, author initials, date, time and the plain text of the comment is combined into one string; you could choose to store it in some other ways instead.
The overloaded method that extracts the Comments from a particular author is almost the same, it just checks the author’s name before adding the info into the array. The code example given below extracts the author’s name, date&time and text of the comments by the specified author.
If you are removing all comments, there is no need to move through the collection deleting comments one by one; you can remove them by calling NodeCollection.Clear on the comments collection. The code example given below removes all comments in the document.
For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C | |
void RemoveComments(const System::SharedPtr<Document>& doc) | |
{ | |
// Collect all comments in the document | |
System::SharedPtr<NodeCollection> comments = doc->GetChildNodes(NodeType::Comment, true); | |
// Remove all comments. | |
comments->Clear(); | |
} |
When you need to selectively remove comments, the process becomes more similar to the code we used for comment extraction. The code example given below removes comments by the specified author.
The main point to highlight here is the use of the for operator. Unlike the simple extraction, here you want to delete a comment. A suitable trick is to iterate the collection backwards from the last Comment to the first one. The reason for this if you start from the end and move backwards, the index of the preceding items remains unchanged, and you can work your way back to the first item in the collection. The demo-code that illustrates the methods for the comments extraction and removal. You can download the template file of this example from here.
For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C | |
// The path to the documents directories. | |
System::String inputDataDir = GetInputDataDir_WorkingWithComments(); | |
System::String outputDataDir = GetOutputDataDir_WorkingWithComments(); | |
// Open the document. | |
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"TestFile.doc"); | |
// Extract the information about the comments of all the authors. | |
for (System::String const &comment : ExtractComments(doc)) | |
{ | |
std::cout << comment.ToUtf8String(); | |
} | |
// Remove comments by the "pm" author. | |
RemoveComments(doc, u"pm"); | |
std::cout << "Comments from \"pm\" are removed!" << std::endl; | |
// Extract the information about the comments of the "ks" author. | |
for (System::String const &comment: ExtractComments(doc, u"ks")) | |
{ | |
std::cout << comment.ToUtf8String(); | |
} | |
//Read the comment's reply and resolve them. | |
CommentResolvedandReplies(doc); | |
// Remove all comments. | |
RemoveComments(doc); | |
std::cout << "All comments are removed!" << std::endl; | |
System::String outputPath = outputDataDir + u"ProcessComments.doc"; | |
// Save the document. | |
doc->Save(outputPath); |
How to Add a Comment
The code example given below shows how to add a comment to a paragraph in the document.
For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C | |
// The path to the documents directory. | |
System::String outputDataDir = GetOutputDataDir_WorkingWithComments(); | |
System::SharedPtr<Document> doc = System::MakeObject<Document>(); | |
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc); | |
builder->Write(u"Some text is added."); | |
System::SharedPtr<Comment> comment = System::MakeObject<Comment>(doc, u"Awais Hafeez", u"AH", System::DateTime::get_Today()); | |
builder->get_CurrentParagraph()->AppendChild(comment); | |
comment->get_Paragraphs()->Add(System::MakeObject<Paragraph>(doc)); | |
comment->get_FirstParagraph()->get_Runs()->Add(System::MakeObject<Run>(doc, u"Comment text.")); | |
System::String outputPath = outputDataDir + u"AddComments.doc"; | |
// Save the document. | |
doc->Save(outputPath); |
The code example given below shows how to anchor a comment to a region of text.
For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C | |
// The path to the documents directory. | |
System::String outputDataDir = GetOutputDataDir_WorkingWithComments(); | |
System::SharedPtr<Document> doc = System::MakeObject<Document>(); | |
System::SharedPtr<Paragraph> para1 = System::MakeObject<Paragraph>(doc); | |
System::SharedPtr<Run> run1 = System::MakeObject<Run>(doc, u"Some "); | |
System::SharedPtr<Run> run2 = System::MakeObject<Run>(doc, u"text "); | |
para1->AppendChild(run1); | |
para1->AppendChild(run2); | |
doc->get_FirstSection()->get_Body()->AppendChild(para1); | |
System::SharedPtr<Paragraph> para2 = System::MakeObject<Paragraph>(doc); | |
System::SharedPtr<Run> run3 = System::MakeObject<Run>(doc, u"is "); | |
System::SharedPtr<Run> run4 = System::MakeObject<Run>(doc, u"added "); | |
para2->AppendChild(run3); | |
para2->AppendChild(run4); | |
doc->get_FirstSection()->get_Body()->AppendChild(para2); | |
System::SharedPtr<Comment> comment = System::MakeObject<Comment>(doc, u"Awais Hafeez", u"AH", System::DateTime::get_Today()); | |
comment->get_Paragraphs()->Add(System::MakeObject<Paragraph>(doc)); | |
comment->get_FirstParagraph()->get_Runs()->Add(System::MakeObject<Run>(doc, u"Comment text.")); | |
System::SharedPtr<CommentRangeStart> commentRangeStart = System::MakeObject<CommentRangeStart>(doc, comment->get_Id()); | |
System::SharedPtr<CommentRangeEnd> commentRangeEnd = System::MakeObject<CommentRangeEnd>(doc, comment->get_Id()); | |
run1->get_ParentNode()->InsertAfter(commentRangeStart, run1); | |
run3->get_ParentNode()->InsertAfter(commentRangeEnd, run3); | |
commentRangeEnd->get_ParentNode()->InsertAfter(comment, commentRangeEnd); | |
System::String outputPath = outputDataDir + u"AnchorComment.doc"; | |
// Save the document. | |
doc->Save(outputPath); |
How to Remove Text between CommentRangeStart and CommentRangeEnd
The code example given below shows how to remove text between CommentRangeStart and CommentRangeEnd nodes.
For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C | |
// The path to the documents directories. | |
System::String inputDataDir = GetInputDataDir_WorkingWithComments(); | |
System::String outputDataDir = GetOutputDataDir_WorkingWithComments(); | |
// Open the document. | |
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"TestFile.doc"); | |
System::SharedPtr<CommentRangeStart> commentStart = System::DynamicCast<CommentRangeStart>(doc->GetChild(NodeType::CommentRangeStart, 0, true)); | |
System::SharedPtr<CommentRangeEnd> commentEnd = System::DynamicCast<CommentRangeEnd>(doc->GetChild(NodeType::CommentRangeEnd, 0, true)); | |
System::SharedPtr<Node> currentNode = commentStart; | |
bool isRemoving = true; | |
while (currentNode != nullptr && isRemoving) | |
{ | |
if (currentNode->get_NodeType() == NodeType::CommentRangeEnd) | |
{ | |
isRemoving = false; | |
} | |
System::SharedPtr<Node> nextNode = currentNode->NextPreOrder(doc); | |
currentNode->Remove(); | |
currentNode = nextNode; | |
} | |
System::String outputPath = outputDataDir + u"RemoveRegionText.doc"; | |
// Save the document. | |
doc->Save(outputPath); |
How to Read Comment’s Reply
Comment.Replies property returns a collection of Comment objects that are immediate children of the specified comment. The code example given below shows how to iterate through a comment’s replies and resolved them.
For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C | |
void CommentResolvedandReplies(const System::SharedPtr<Document>& doc) | |
{ | |
System::SharedPtr<NodeCollection> comments = doc->GetChildNodes(NodeType::Comment, true); | |
System::SharedPtr<Comment> parentComment = System::DynamicCast<Comment>(comments->idx_get(0)); | |
for (System::SharedPtr<Comment> childComment : System::IterateOver<System::SharedPtr<Comment>>(parentComment->get_Replies())) | |
{ | |
// Get comment parent and status. | |
std::cout << childComment->get_Ancestor()->get_Id() << std::endl << childComment->get_Done() << std::endl; | |
// And update comment Done mark. | |
childComment->set_Done(true); | |
} | |
} |
How to Add and Remove Comment’s Reply
The Comment.AddReply method adds a reply to this comment. Please note that due to the existing MS Office limitations only 1 level of replies are allowed in the document. An exception of type InvalidOperationException will be raised if this method is called on the existing Reply comment.
You can use Comment.RemoveReply method to remove the specified reply to this comment. The following code example shows how to add a reply to a comment and remove the comment’s reply.
For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C | |
// The path to the documents directories. | |
System::String inputDataDir = GetInputDataDir_WorkingWithComments(); | |
System::String outputDataDir = GetOutputDataDir_WorkingWithComments(); | |
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"TestFile.doc"); | |
System::SharedPtr<Comment> comment = System::DynamicCast<Comment>(doc->GetChild(NodeType::Comment, 0, true)); | |
//Remove the reply | |
comment->RemoveReply(comment->get_Replies()->idx_get(0)); | |
//Add a reply to comment | |
comment->AddReply(u"John Doe", u"JD", System::DateTime(2017, 9, 25, 12, 15, 0), u"New reply"); | |
System::String outputPath = outputDataDir + u"CommentReply.doc"; | |
// Save the document to disk. | |
doc->Save(outputPath); |