Free Support Forum - aspose.com

Comment End of the Word in Paragraph using Java | Add Comment in Word Document

Dear Team,

i am getting array index out of bounds exception while insert comment for the end of the word in the paragraph . I am trying to insert comments based on the word position.

My code

public static void commentRangeOfRuns(Paragraph para,HashMap<String, String>position) {

	Document doc = (Document) para.getDocument();
	DocumentBuilder builder=new DocumentBuilder(doc);
	Node[] runs = para.getChildNodes(21, true).toArray();
			
	for(Map.Entry<String, String> entry:position.entrySet()) {
		String commentText=entry.getKey();
		String []positionary=entry.getValue().split("_");
		int start=Integer.valueOf(positionary[0]);
		int end=Integer.valueOf(positionary[1]);
		for(int i=start;i<end;i++) {
			System.out.print(runs[i].getText());
		}
		Comment comment = new Comment((DocumentBase) doc, "comment", "LE", new Date());
		comment.getParagraphs().add((Node) new Paragraph((DocumentBase) doc));
		comment.getFirstParagraph().getRuns().add((Node) new Run((DocumentBase) doc, commentText));
		CommentRangeStart commentRangeStart = new CommentRangeStart((DocumentBase) doc, comment.getId());
		CommentRangeEnd commentRangeEnd = new CommentRangeEnd((DocumentBase) doc, comment.getId());
		runs[start - 0].getParentNode().insertBefore((Node) commentRangeStart, runs[start - 0]);
		runs[end - 0].getParentNode().insertBefore((Node) commentRangeEnd, runs[end - 0]);
		commentRangeEnd.getParentNode().insertAfter((Node) comment, (Node) commentRangeEnd);
	}
	
}

Thanks in advance

Best regards,
Kesavaraman

@keshav07,

To ensure a timely and accurate response, please ZIP and attach the following resources here for testing:

  • Your simplified input Word document
  • Your expected DOCX file showing the desired output. You can create this document by using MS Word.

As soon as you get these pieces of information ready, we will start investigation into your scenario and provide you code to achieve the same by using Aspose.Words for Java. Thanks for your cooperation.