Friday, 14 February 2020 07:39

Add Comment to Specific Text in Word in Java

Written by  support iceblue
Rate this item
(0 votes)

Spire.Doc for Java supports adding comment to a paragraph as well as adding comment to a specific text in a Word document. This article demonstrates how to add comment to a specific text in a Word document using Spire.Doc for Java.

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 AddComments {
    public static void main(String[] args){
        //Load a Word document
        Document doc = new Document();
        doc.loadFromFile("input.docx");

        //Find the string “Spire.Doc for Java”  in the document
        TextSelection[] finds = doc.findAllString("Spire.Doc for Java", false, true);

        for (TextSelection find : finds) {
            //Create comment start mark and comment end mark
            CommentMark commentmarkStart = new CommentMark(doc);
            commentmarkStart.setType(CommentMarkType.Comment_Start);
            CommentMark commentmarkEnd = new CommentMark(doc);
            commentmarkEnd.setType(CommentMarkType.Comment_End);

            //Create a comment
            Comment comment = new Comment(doc);
            comment.getBody().addParagraph().setText("Developed by E-iceblue");
            comment.getFormat().setAuthor("Shaun");

            //Find the paragraph where the string is located in
            Paragraph para = find.getAsOneRange().getOwnerParagraph();
            //Get the index of the string in the paragraph
            int index = para.getChildObjects().indexOf(find.getAsOneRange());

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

        //Save the result document
        doc.saveToFile("result.docx",FileFormat.Docx_2013);
    }
}

Output:

Add Comment to Specific Text in Word in Java

Additional Info

  • tutorial_title: