This simple tutorial briefs on how to add comments in Word using Java. You can set different advanced properties of the comments available for a Word file and save the file again as DOCX. Here are the steps on how to insert comment in Word using Java.
Steps to Add Comments in Word using Java
- Add Aspose.Words from the Maven repository to insert comments
- Open the source Word file using the Document class object
- Move the cursor to the target paragraph
- Insert comment in Word document paragraph using Java
- Save the file after adding the comments
Using these steps we open a Word document and initialize the DocumentBuilder object that can be used to access different elements of the Word file like its paragraphs. We can move cursor to any element that mimics the cursor movement in MS Word manually. Finally we add the comments and save the Word file.
Code to Add Comments to Word Document using Java
import com.aspose.words.License; | |
import com.aspose.words.Document; | |
import com.aspose.words.DocumentBuilder; | |
import com.aspose.words.Comment; | |
import com.aspose.words.Paragraph; | |
import com.aspose.words.Run; | |
import java.util.Date; | |
public class HowToAddCommentsInWordUsingJava | |
{ | |
public static void main(String[] args) throws Exception { //main function for AddImageInWord class | |
// Initialize a license to avoid trial version watermark in the output Word file after adding image | |
License license = new License(); | |
license.setLicense("Aspose.Words.lic"); | |
// Load the Word document where comments are to be added | |
Document DocumentForComment = new Document("input.docx"); | |
DocumentBuilder builder = new DocumentBuilder(DocumentForComment); | |
// Move the cursor to the beginning of the document for adding comments | |
builder.moveToDocumentStart(); | |
// Insert comment to first paragraph of document by providing Author, Initial, time and comment text | |
Comment comment = new Comment(DocumentForComment, "Aspose.Words", "AW", new Date()); | |
builder.getCurrentParagraph().appendChild(comment); | |
comment.getParagraphs().add(new Paragraph(DocumentForComment)); | |
comment.getFirstParagraph().getRuns().add(new Run(DocumentForComment, "Comment text.")); | |
// Save the Document with comments | |
DocumentForComment.save("OutputDocumentWithComments.docx"); | |
} | |
} |
In this Java code, we used Comment class object that contains all the properties required to configure a comment in the Word document. We provide Author name, initial of the user, time of comments and then finally set the comments text.
In this step-by-step tutorial, we opened an existing file and added comments to it. If you want to learn more features like adding row to a table, refer to the article on how to add a row to a table in Word using Java. Note that no MS Word or Interop is required on the system to run the above code.