This article presents how to add a comment, reply to a comment, change or remove a comment in Word in C#.
Introduction
MS Word allows you to insert a comment inside a
balloon or a box that appears in the document margins. A comment can be added to
a piece of text or an item as a note to this part of the document. This article
is going to introduce how we can add a comment to a paragraph, reply to a
comment, and change or remove a comment by using Spire.Doc in C#.Using the code
Part 1. Add a comment to a paragraph
//Initialize an instance of Document class
Document doc = new Document();
//Load a Word document
doc.LoadFromFile("template.docx");
//Get the paragraph that you want to add comment
Paragraph para = doc.Sections[0].Paragraphs[6];
//Insert a start comment mark at the beginning of the paragraph
CommentMark startCommentMark = new CommentMark(doc);
startCommentMark.Type = CommentMarkType.CommentStart;
para.ChildObjects.Insert(0, startCommentMark);
//Add an end comment mark at the end of the paragraph
CommentMark endCommentMark = new CommentMark(doc);
endCommentMark.Type = CommentMarkType.CommentEnd;
para.ChildObjects.Add(endCommentMark);
//Add a comment to the paragraph and specify the content and author
Comment comment = new Comment(doc);
comment.Body.AddParagraph().AppendText("This paragraph explains how to write an abstract.");
comment.Format.Author = "John";
para.ChildObjects.Add(comment);
//Save to file
doc.SaveToFile("CommentOnPara.docx", FileFormat.Docx2013);
Figure 1. Add a comment
Part 2. Add a reply to a comment
//Initialize an instance of Document class
Document doc = new Document();
//Load the Word document generated in part 1
doc.LoadFromFile("CommentOnPara.docx");
//Get the comment by its index
Comment comment = doc.Comments[0];
//Create a new comment
Comment replyComment = new Comment(doc);
replyComment.Format.Author = "Adam";
replyComment.Body.AddParagraph().AppendText("Exactly.");
//Add the new comment as a reply to the existing comment
comment.ReplyToComment(replyComment);
//Save to file.
doc.SaveToFile("ReplyToComment.docx", FileFormat.Docx2013);
Figure 2. Reply to a comment
Part 3: Modify or remove a comment
//Initialize an instance of Document class
Document doc = new Document();
//Load the Word document generated in part 1
doc.LoadFromFile("CommentOnPara.docx");
//Get the comment by its index
Comment comment = doc.Comments[0];
//Assign new string to comment text
comment.Body.Paragraphs[0].Text = "This comment is changed.";
//Save to file.
doc.SaveToFile("ModifyComment.docx", FileFormat.Docx2013);
Figure 3. Modify a comment
To remove all comments in a Word document, call CommentsCollection.Clear(). To remove an specific comment, just call CommentsCollection.RemoveAt(int index) method.
Conclusion
It is possible but a bit difficult to add a comment to a selected range of text such as a phrase or a sentence, because we can hardly locate the text and place comment marks at the both ends by using this API.
Thanks for reading.