Add Comments to Text in Word Using Java


Sample Code

The Paragraph.appendComment() method is used to add comments to an entire paragraph. By default, the comment mark will be placed at the end of the paragraph. To add a comment to a specific phrase, you need to place comment marks (represented by the CommentMark class) at the beginning and end of the text range.

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.documents.CommentMark;
import com.spire.doc.documents.CommentMarkType;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.TextSelection;
import com.spire.doc.fields.Comment;

public class AddCommentToSpecificText {

public static void main(String[] args) {

//Create a Document object
Document doc = new Document();

//Load the sample Word file

//Find the specific string to add comment
TextSelection[] finds = doc.findAllString("Olympic Games", false, true);
TextSelection specificText = finds[0];

//Create a start mark
CommentMark commentmarkStart = new CommentMark(doc);

//Create an end mark
CommentMark commentmarkEnd = new CommentMark(doc);

//Create a comment
Comment comment = new Comment(doc);
comment.getBody().addParagraph().setText("modern Olympic Games or Olympics ");

//Find the paragraph where the string is located
Paragraph para = specificText.getAsOneRange().getOwnerParagraph();

//Get the index of the string in the paragraph
int index = para.getChildObjects().indexOf(specificText.getAsOneRange());

//Add the comment to the paragraph

//Insert the start mark and end mark to the paragraph based on the index
para.getChildObjects().insert(index, commentmarkStart);
para.getChildObjects().insert(index + 2, commentmarkEnd);

//Save to file
doc.saveToFile("AddComment.docx", FileFormat.Docx_2013);



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store