I want to apply comment on particular text in word document

Hi,
This is the line (This is the text Please add comment on Me and Also on Me) I want to add comment on particular text e.g on Me. How can i do that using c#

@Amrinder_Singh You can achieve this using IReplacingCallback. For example see the following code:

Document doc = new Document(@"C:\Temp\in.docx");

FindReplaceOptions opt = new FindReplaceOptions();
opt.Direction = FindReplaceDirection.Backward;
opt.ReplacingCallback = new ReplaceEvaluatorWrapWithComment();
opt.FindWholeWordsOnly = true;

doc.Range.Replace("Me", "Some comment", opt);

doc.Save(@"C:\Temp\out.docx");
internal class ReplaceEvaluatorWrapWithComment : IReplacingCallback
{
    /// <summary>
    /// This method is called by the Aspose.Words find and replace engine for each match.
    /// </summary>
    ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)
    {
        Document doc = (Document)e.MatchNode.Document;

        // This is a Run node that contains either the beginning or the complete match.
        Node currentNode = e.MatchNode;

        // The first (and may be the only) run can contain text before the match, 
        // in this case it is necessary to split the run.
        if (e.MatchOffset > 0)
            currentNode = SplitRun((Run)currentNode, e.MatchOffset);

        // This array is used to store all nodes of the match for further deleting.
        List<Run> runs = new List<Run>();

        // Find all runs that contain parts of the match string.
        int remainingLength = e.Match.Value.Length;
        while (
            remainingLength > 0 &&
            currentNode != null &&
            currentNode.GetText().Length <= remainingLength)
        {
            runs.Add((Run)currentNode);
            remainingLength -= currentNode.GetText().Length;

            // Select the next Run node.
            // Have to loop because there could be other nodes such as BookmarkStart etc.
            do
            {
                currentNode = currentNode.NextSibling;
            } while (currentNode != null && currentNode.NodeType != NodeType.Run);
        }

        // Split the last run that contains the match if there is any text left.
        if (currentNode != null && remainingLength > 0)
        {
            SplitRun((Run)currentNode, remainingLength);
            runs.Add((Run)currentNode);
        }

        // Create comment.
        Comment comment = new Comment(doc, "Alexey", "AN", DateTime.Now);
        // Add some content to the comment.
        comment.EnsureMinimum();
        comment.FirstParagraph.AppendChild(new Run(doc, e.Replacement));

        // Create comment range start and end.
        CommentRangeStart start = new CommentRangeStart(doc, comment.Id);
        CommentRangeEnd end = new CommentRangeEnd(doc, comment.Id);

        // Wrap matched content with comment.
        runs[0].ParentNode.InsertBefore(start, runs[0]);
        runs[0].ParentNode.InsertBefore(comment, runs[0]);
        runs[runs.Count-1].ParentNode.InsertAfter(end, runs[runs.Count-1]);

        // Signal to the replace engine to do nothing because we have already done all what we wanted.
        return ReplaceAction.Skip;
    }

    private static Run SplitRun(Run run, int position)
    {
        Run afterRun = (Run)run.Clone(true);
        run.ParentNode.InsertAfter(afterRun, run);
        afterRun.Text = run.Text.Substring(position);
        run.Text = run.Text.Substring((0), (0) + (position));
        return afterRun;
    }
}

in.docx (12.4 KB)
out.docx (11.2 KB)

@alexey.noskov I have replies to comments also how can i add them using this approach?

@Amrinder_Singh You could call Comment.AddReply methods after the comment is added to the document model.

// Wrap matched content with comment.
runs[0].ParentNode.InsertBefore(start, runs[0]);
runs[0].ParentNode.InsertBefore(comment, runs[0]);
runs[runs.Count-1].ParentNode.InsertAfter(end, runs[runs.Count-1]);

// Add replies
comment.AddReply("Alexey", "AN", DateTime.Now, "reply1 text");
comment.AddReply("Alexey", "AN", DateTime.Now, "reply2 text");

Can we add comment on whole table itself using aspose?

@Amrinder_Singh Sure, you can wrap whole table into the comment range using Aspose.Words. For example see the following code:

Document doc = new Document(@"C:\Temp\in.docx");

// Get table.
Table table  = doc.FirstSection.Body.Tables[0];

// Create comment and comment range start and end.
Comment comment = new Comment(doc, "John Doe", "JD", DateTime.Now);
// Add some content to the comment.
comment.AppendChild(new Paragraph(doc));
comment.FirstParagraph.AppendChild(new Run(doc, "This is a table."));

CommentRangeStart rangeStart = new CommentRangeStart(doc, comment.Id);
CommentRangeEnd rangeEnd = new CommentRangeEnd(doc, comment.Id);

// Put comment range start at the very beginning of the table and end at the end.
table.FirstRow.FirstCell.FirstParagraph.PrependChild(rangeStart);
table.LastRow.LastCell.FirstParagraph.AppendChild(rangeEnd);
table.LastRow.LastCell.FirstParagraph.AppendChild(comment);

doc.Save(@"C:\Temp\out.docx");

Thank for the reply it is working all well.
Can we do the same for image also?

@Amrinder_Singh Sure, you can achieve this using the following code:

Document doc = new Document(@"C:\Temp\in.docx");

// Get shape.
Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true);

// Create comment and comment range start and end.
Comment comment = new Comment(doc, "John Doe", "JD", DateTime.Now);
// Add some content to the comment.
comment.AppendChild(new Paragraph(doc));
comment.FirstParagraph.AppendChild(new Run(doc, "This is a Shape."));

CommentRangeStart rangeStart = new CommentRangeStart(doc, comment.Id);
CommentRangeEnd rangeEnd = new CommentRangeEnd(doc, comment.Id);

// Put comment range around the shape.
shape.ParentNode.InsertBefore(rangeStart, shape);
shape.ParentNode.InsertAfter(rangeEnd, shape);
shape.ParentNode.InsertAfter(comment, shape);

doc.Save(@"C:\Temp\out.docx");

Hi,
When I’m adding comments to any text its font family is being changed to new times roman automatically

@Amrinder_Singh Content of comment is create from scratch so default formatting is applied to it. You can change the font in the run’s font properties. For example see the following code:

// Create comment and comment range start and end.
Comment comment = new Comment(doc, "John Doe", "JD", DateTime.Now);
// Add some content to the comment.
comment.AppendChild(new Paragraph(doc));
Run commentText = new Run(doc, "This is a Shape.");
commentText.Font.Name = "Calibri";
commentText.Font.Color = Color.Red;
comment.FirstParagraph.AppendChild(commentText);

It didn’t worked still its coming in new times roman only, i forgot to tell you its converting whole content to new times roman even though if some other text does not contain any comment

@Amrinder_Singh Could you please attach your input, output and expected output documents here for our reference? We will check the issue and provide you more information.

Hi,
i have data like that

<ol>
<li>1</li>
<li>2</li>
</ol>

i insert the above data using builder.InsertHtml and then trying to find the content using replace evaluter method mentioned above in this thread
but in downloaded report comment does not come

@Amrinder_Singh Such content is inserted as a two paragraphs so if it is required to add comment on this content it would be easier to start comment range fore inserting HTML and insert comment range end after inserting HTML, than using IReplacingCallback.