How to add comment in Word document using Java

Hi,
I am new to the Aspose world. I see that there is a way to
create and add content to a word document (.doc). What i am trying to
figure out is if there is any way to “add comments also to the doc” from
our program.

My project basically involves
i) reading .doc file and extracting information and storing it temporarily as txt files.
ii) perform certain operations required to complete my project.
ii) write back the modified data to a .doc file.

I am stuck on step 3, i cannot write back the comments that i extracted in step 1. can anyone help?

BTW, i am using aspos.words for java

Hi,
I am new to the Aspose world. I see that there is a way to create and add content to a word document (.doc). What i am trying to figure out is if there is any way to “add comments also to the doc” from our program.

My project basically involves
i) reading .doc file and extracting information and storing it temporarily as txt files.
ii) perform certain operations required to complete my project.
ii) write back the modified data to a .doc file.

I am stuck on step 3, i cannot write back the comments that i extracted in step 1. can anyone help?

BTW, i am using aspos.words for java

Hi Divyansh,

Please accept my apologies for late response.

Thanks for your query. Please use the following code snippet to add comments in .Doc file. Hope this answers your query. Let us know, If you have any more queries.

public static void addcomments() throws Exception
{
    // Create an empty document and DocumentBuilder object.
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);
    // Create a Comment.
    Comment comment = new Comment(doc);
    // Insert some text into the comment.
    Paragraph commentParagraph = new Paragraph(doc);
    commentParagraph.appendChild(new Run(doc, "This is comment!!!"));
    comment.appendChild(commentParagraph);
    // Create CommentRangeStart and CommentRangeEnd.
    int commentId = 0;
    CommentRangeStart start = new CommentRangeStart(doc, commentId);
    CommentRangeEnd end = new CommentRangeEnd(doc, commentId);
    // Insert some text into the document.
    builder.write("This is text before comment ");
    // Insert comment and comment range start.
    builder.insertNode(comment);
    builder.insertNode(start);
    // Insert some more text.
    builder.write("This is commented text ");
    // Insert end of comment range.
    builder.insertNode(end);
    // And finaly insert some more text.
    builder.write("This is text aftr comment");
    // Save output document.
    doc.save("C:\\out.doc");
}

Please read following forum link for your kind reference.

http://www.aspose.com/community/forums/permalink/300896/300896/showthread.aspx#300896

No, the problem is actually copying all the comments back to the word document. The code snippet shown by you tells me how to add a comment. That part i already had figured out.

The problem is i do not know how many comments are there in the original source document. I save the comments in an arraylist of objects of class commData

public class commData
{
    Comment comment;
    CommentRangeStart start;
    CommentRangeEnd end;
}

Now when i create a new document where i want to write back the comments how do i know where to enter them.
Hope you could help me with this,

Thanks

OKAY, let me rephrase…

the user gives some kind of an input and i want to insert a comment accordingly to the document. is that possible in anyway?
The program takes some input and according to that some portion of text is highlighted.

The code samples you show add text and comments to the document, i need to add comments to an already existing document according to some input from the user.

Hoping for a quick response, i’m stuck in my task right now.

Hi Divyansh,

Thanks for sharing the further information. Please use the following code snippet to read comments from a document and insert into another document.

// Open input document.
Document doc = new Document("C:\\Temp\\in.doc");
// open document where we will copy paragraphs with comments.
Document dst = new Document("C:\\Temp\\Document1.doc");
// Create an importer that will allow us to copy nodes from source document to destination.
NodeImporter importer = new NodeImporter(doc, dst, ImportFormatMode.KEEP_SOURCE_FORMATTING);
// Get all comments from the source document.
Node[] comments = doc.getChildNodes(NodeType.COMMENT, true).toArray();
// Loop through all comments and copy paragraph that contains these comments to the dst doc.
for (Node commentNode: comments)
{
    // Get parent paragraph and copy it to the dst doc.
    Node dstNode = importer.importNode(commentNode.getAncestor(NodeType.PARAGRAPH), true);
    // Insert imported node to the destination document.
    dst.getFirstSection().getBody().appendChild(dstNode);
}
// Save output document.
dst.save("C:\\Temp\\out.doc");

Hi Tahir, thank you for the quick response.

But this code that you showed here copies one document entirely to the other. What I need is to add comments to an existing document (that does not already have the comments).

Say, I need a particular word in a particular paragraph to be commented out through my Java program, how do i achieve that? How should i initialise my CommentRangeStart and CommentRangeEnd objects in order to achieve this?

I hope you’re understanding the problem here.
Waiting for a response, i’ve been stuck here for almost a week now. Hope aspose.words has a solution for this.

Thanks.

Hi Divyansh,

Say, I need a particular word in a particular paragraph to be commented
out through my Java program, how do i achieve that? How should i
initialise my CommentRangeStart and CommentRangeEnd objects in order to
achieve this?

Please accept my apologies for misunderstanding. I have tried to understand your problem statement and base on my understanding you need the followings. Please correct me If I am wrong.

  1. You have a document with specific text in it
  2. You want to find that specific text
  3. Add comments to that specific text
  4. The comments are in an array list or comments are from another document.
Node[] comments = doc.getChildNodes(NodeType.COMMENT, true).toArray();

Please elaborate your query with some more details. We are really keen to help you but need some more detail from your side.

Thank you for replying, I really am desperate to get out of this mess.
The problem is basically to add comments to an already existing document.

I’ll try and elaborate the problem

  1. A word document already exists on disk.
  2. I need to add comments to that document through my java program.
  3. The comment (to begin with) is a string only, but I do know where to add the comment (I have the paragraph number, the word number in the paragraph where the comment begins and the word where it ends).

eg.
This “is a” sample.
–> If “is a” contains a comment, i know the paragraph number to which this statement belongs and also the index of the words that need to be commented. In this case, (2,3) is the range specifying words 2 - 3 being commented. But how do i actually add the comment to the doc using these parameters?

Now, I’ve tried creating Comment nodes and attaching it to a paragraph but that adds the comment to the end of the paragraph. I need to attach the comment to the specific words.

Help!!!

Also, the comments are not from another document. They are just String objects defined within my program.

In layman’s language, If I am provided with the comment contents, the paragraph number where the comment needs to be added and the word range (2,3) as explained above. How do I go about adding the comment to the document?

Hi Divyansh,

Please use the following code snippet to add comment to a paragraph in a document. I have attached the input and output document with this post. Please let us know, If you have any more queries.

// Open an existing document to add comments to a paragraph.
Document doc = new Document("D:\\in.doc");
Node[] nodes = doc.getChildNodes(NodeType.PARAGRAPH, true).toArray();
// E.g this is the Paragraph to which comments will added
Paragraph paragraph = (Paragraph) nodes[4];
DocumentBuilder builder = new DocumentBuilder(doc);
// Create a Comment.
Comment comment = new Comment(doc);
// Insert some text into the comment.
Paragraph commentParagraph = new Paragraph(doc);
commentParagraph.appendChild(new Run(doc, "This is comment!!!"));
comment.appendChild(commentParagraph);
// Move to paragraph where comments will be added
builder.moveTo(paragraph);
// Insert comment
builder.insertNode(comment);
// Save output document.
doc.save("D:\\AsposeOut.doc");

yes, this shows me how to reach the paragraph.

but how do i select some portion of text that needs to be commented? all i have is the starting and ending locations (int) of the area that needs to be commented out.

Hi Divyansh,

Please accept my apologies for late response. Please use the following code snippet to select a portion of text and add comments.

// Open an existing document to add comments to a paragraph.
Document doc = new Document("D:\\in.doc");
Node[] nodes = doc.getChildNodes(NodeType.PARAGRAPH, true).toArray();
// E.g this is the Pragraph to which comments will added
Paragraph paragraph = (Paragraph) nodes[4];
DocumentBuilder builder = new DocumentBuilder(doc);
// Create a Comment.
Comment comment = new Comment(doc);
// Insert some text into the comment.
Paragraph commentParagraph = new Paragraph(doc);
commentParagraph.appendChild(new Run(doc, "This is comment!!!"));
comment.appendChild(commentParagraph);
// Create CommentRangeStart and CommentRangeEnd.
int commentId = 0;
CommentRangeStart start = new CommentRangeStart(doc, commentId);
CommentRangeEnd end = new CommentRangeEnd(doc, commentId);
Run firstRun = paragraph.getRuns().get(0);
Run lastRun = paragraph.getRuns().get(paragraph.getRuns().toArray().length - 1);
firstRun.getParentNode().insertBefore(comment, firstRun);
firstRun.getParentNode().insertBefore(start, firstRun);
lastRun.getParentNode().insertAfter(end, lastRun);
// Save output document.
doc.save("D:\\AsposeOut.doc");

Alright, Thank you.
Doesn’t actually solve my problem but gives me an idea regarding what can be done.

Much Appreciated Tahir, Thank you.
Divyansh

Hi Tahir,

I have a document with 5 paragraphs with different styles. I would like add a comment to the whole paragraph if the style is heading 1. I sort of got it working with the following code. I uploaded the output document as attachment. The 1st paragraph with heading 1 is highlighted correctly but only the first sentence in the second paragraph with heading 1 (4th paragraph in the document) is underlined with the comment. Can you tell me what I need to do to get both paragraph with heading 1 hightlighted please?

Document document = new Document(filePath);

NodeCollection nodes = document.getChildNodes(NodeType.PARAGRAPH, true);

for (int i = 0; i <nodes.getCount(); i++)
{
    Paragraph paragraph = (Paragraph) nodes.get(i);

    String style = paragraph.getParagraphFormat().getStyle().getName();
    System.out.println(style);

    int commentId = 0;
    if ("Heading 1".equals(style))
    {
        StringBuilder sb = new StringBuilder("Paragraph style '" + style + "' isn't valid in this template.");
        Comment comment = new Comment(document);
        comment.setAuthor("AUTO");
        Paragraph commentParagraph = new Paragraph(document);
        commentParagraph.appendChild(new Run(document, sb.toString()));
        comment.appendChild(commentParagraph);

        CommentRangeStart start = new CommentRangeStart(document, commentId);
        CommentRangeEnd end = new CommentRangeEnd(document, commentId);

        Run firstRun = paragraph.getRuns().get(0);
        Run lastRun = paragraph.getRuns().get(paragraph.getRuns().getCount() - 1);
        firstRun.getParentNode().insertBefore(comment, firstRun);
        firstRun.getParentNode().insertBefore(start, firstRun);
        lastRun.getParentNode().insertAfter(end, lastRun);
        commentId++;
    }
}

document.save("C:/temp/document1.doc");

Thanks

Hi Alex,

Thanks for your inquiry. Please use the Comment.comment.getId() in CommentRangeStart and CommentRangeEnd Constructor. This will solve your problem. Please let us know if you have any more queries.

Document document = new Document(MyDir + "in.docx");

NodeCollection nodes = document.getChildNodes(NodeType.PARAGRAPH, true);
for (int i = 0; i <nodes.getCount(); i++)
{
    Paragraph paragraph = (Paragraph) nodes.get(i);
    String style = paragraph.getParagraphFormat().getStyle().getName();
    System.out.println(style);
    if ("Heading 1".equals(style))
    {
        StringBuilder sb = new StringBuilder("Paragraph style '" + style + i + "' isn't valid in this template.");
        Comment comment = new Comment(document);
        comment.setAuthor("AUTO");
        Paragraph commentParagraph = new Paragraph(document);
        commentParagraph.appendChild(new Run(document, sb.toString()));
        comment.appendChild(commentParagraph);
        CommentRangeStart start = new CommentRangeStart(document, comment.getId());
        CommentRangeEnd end = new CommentRangeEnd(document, comment.getId());
        Run firstRun = paragraph.getRuns().get(0);
        Run lastRun = paragraph.getRuns().get(paragraph.getRuns().getCount() - 1);
        firstRun.getParentNode().insertBefore(comment, firstRun);
        firstRun.getParentNode().insertBefore(start, firstRun);
        lastRun.getParentNode().insertAfter(end, lastRun);
    }
}
document.save(MyDir + "out.docx");

Hi Tahir,

Thanks for the solution. It worked. For some reason commentId variable isn’t incremented.

Hi Alex,

Thanks for your inquiry. The CommentRangeStart constructor initializes a new instance of CommentRangeStart. The second parameter is comment identifier to which this object is linked. You should not use local variable for comment identifier.

Moreover, when CommentRangeStart is created, it belongs to the specified document, but is not yet part of the document and ParentNode is null. To append a CommentRangeStart to the document use InsertAfter or InsertBefore on the paragraph where you want the comment inserted.

Please feel free to ask if you have any question about Aspose.Words, we will be happy to help you.

Hi,

I do face a similar situation, I need to insert a set of comments to a particular part of the document. Assume in a paragraph i need to write a comment for a word also need to write a reply comment also is this is possible in ASPOSE words.