Add Comments to Text in Word Using Java

<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc.free</artifactId>
<version>5.1.0</version>
</dependency>
</dependencies>

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
doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Olympics.docx");

//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);
commentmarkStart.setType(CommentMarkType.Comment_Start);

//Create an end mark
CommentMark commentmarkEnd = new CommentMark(doc);
commentmarkEnd.setType(CommentMarkType.Comment_End);

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

//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
para.getChildObjects().add(comment);

//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