In Aspose.Words find the specific text in word document and add the comment to that text using c#

In Aspose.Words find the specific text in word document and add the comment to that text using c#

Hi Rambabu,

Thanks for your inquiry. Please use the following code to find the specific text in word document and add the comment to that text using C#:

Document doc = new Document("D:\\temp\\input.docx");
FindReplaceOptions opts = new FindReplaceOptions();
opts.Direction = FindReplaceDirection.Backward;
opts.ReplacingCallback = new ReplaceEvaluator();
doc.Range.Replace(new Regex("Process me"), "", opts);
doc.Save("D:\\temp\\18.11-commented.docx");
private class ReplaceEvaluator : IReplacingCallback
{
    ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)
    {
        // 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 removing.
        ArrayList runs = new ArrayList();
        // 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(currentNode);
            remainingLength = 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(currentNode);
        }
        Comment comment = new Comment(e.MatchNode.Document, "Awais Hafeez", "AH", DateTime.Today);
        comment.Paragraphs.Add(new Paragraph(e.MatchNode.Document));
        comment.FirstParagraph.Runs.Add(new Run(e.MatchNode.Document, "Comment text."));
        CommentRangeStart commentRangeStart = new CommentRangeStart(e.MatchNode.Document, comment.Id);
        CommentRangeEnd commentRangeEnd = new CommentRangeEnd(e.MatchNode.Document, comment.Id);
        Run runStart = (Run)runs[0];
        Run runEnd = (Run)runs[runs.Count - 1];
        runStart.ParentNode.InsertBefore(commentRangeStart, runStart);
        runEnd.ParentNode.InsertAfter(commentRangeEnd, runEnd);
        commentRangeEnd.ParentNode.InsertAfter(comment, commentRangeEnd);
        return ReplaceAction.Skip;
    }
}

Hi Hafeez,

Thank you very much for your valuable response…but here i have a one concern if i validate 18 pages of word document all pages are not validating. once we save the validated document we have only 6 pages and it it showing the following message. Please suggest me on this what i need to do.

This
document was truncated here because it was created using Aspose.Words in
Evaluation Mode.

Thanks,

Rambabu

Hi Rambabu,

Thanks for your inquiry. This is because you’re using Aspose.Words in evaluation mode (without applying a license). Please refer to the following topic:

Evaluate Aspose.Words

Best regards,

Hi Hafeez,

Thanks for your wonderful support. I am working with Temporary licence. Problem got resolved.

I am am checking the below requirement with temporary licence.

“I have a table in Word document, In this table if we have any Blank cells we need to add the Text N/A and need to add the comment to that Blank cell like the functionality which is available in MS Word”.

If you have any Idea if this feature is available in Aspose.Words.

Thanks,

Rambabu

Hi Rambabu,

Thanks for your inquiry. Sure, you can insert string “N/A” to blank cells using the following code:

Document doc = new Document(filePath);
Table tbl = doc.FirstSection.Body.Tables[0];
foreach (Row row in tbl)
{
    foreach (Cell cell in row)
    {
        if (string.IsNullOrEmpty(cell.ToString(SaveFormat.Text).Trim()))
        {
            cell.RemoveAllChildren();
            cell.EnsureMinimum();
            cell.FirstParagraph.Runs.Add(new Run(doc, "N/A"));
        }
    }
}
doc.Save(MyDir + @"16.4.0.docx");

Secondly, please refer to the following article:

Working with Comments using Aspose.Words

Best regards,

Thank You Very Much Hafeez…

Hi Hafeez,

I am trying to execute the parallel programming using like “Parallel.Invoke(() => Method1(), () => Method2(), () => Method3());” I am using Same class “ReplaceEvaluator” for 3 methods but i am getting an error saying “Cannot add style because a style with the same name already exists”.I am using same word document for different evaluations.

I am getting error at this step.

Aspose.Words.Comment comment = new Aspose.Words.Comment((Aspose.Words.Document)e.MatchNode.Document, strAuthor, Initial, DateTime.Now);

if you have any idea please let me know.

Thanks,

Rambabu

Hi Rambabu,

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

  • Your input Word document
  • Please create a standalone console application (source code without compilation errors) that helps us reproduce your problem on our end and attach it here for testing.

As soon as you get these pieces of information ready, we’ll start investigation into your issue and provide you more information. Thanks for your cooperation.

PS: To attach these resources, please zip them and Click ‘Reply’ button that will bring you to the ‘reply page’ and there at the bottom you can include any attachments with that post by clicking the ‘Add/Update’ button.

Best regards,

Hi Hafeez,

Need one more help…I have a data in word document(it has 100 pages) it contains dates as well in that data. I need only dates. How we can fetch only dates i don’t need any other data.

Thanks,

Rambabu

Hi Hafeez,

Is there any way to read the document and comment when we zip and unzip the word document.

If we zip and Unzip the word document. The files will generate in xml format. that files i want to read it. Is it possible by using Aspose.Words

  1. Enable the extensions in Folder and search options.

  2. Change the word doc extension to .Zip

  3. Unzip it.

once unzip the files will generate which is attached in screen-shot. i want to read that and comment it of document file for performance purpose.

Please find the attached screens-shot for your reference.

Thanks,

Rambabu

Boyapati:

Hi Hafeez,

Need one more help…I have a data in word document(it has 100 pages) it contains dates as well in that data. I need only dates. How we can fetch only dates i don’t need any other data.

Thanks,

Rambabu

Hi Rambabu,

Thanks for your inquiry. You can get date field values by using the following code:

Document doc = new Document(filePath);
foreach (Field field in doc.Range.Fields)
{
    if (field.Type == FieldType.FieldDate)
    {
        FieldDate date = (FieldDate)field;
        // use different properties of date field
    }
}

Hope, this helps.

Best regards,

Boyapati:

Hi Hafeez,

Is there any way to read the document and comment when we zip and unzip the word document.

If we zip and Unzip the word document. The files will generate in xml format. that files i want to read it. Is it possible by using Aspose.Words

1) Enable the extensions in Folder and search options.

2) Change the word doc extension to .Zip

3) Unzip it.

once unzip the files will generate which is attached in screen-shot. i want to read that and comment it of document file for performance purpose.

Please find the attached screens-shot for your reference.

Thanks,

Rambabu

Hi Rambabu,

Thanks for your inquiry. It is not possible to read individual XML files. However, Aspose.Words reads these files and builds DOM in memory. You can use different DOM classes if you want to read comments or any other elements found in your document. I would suggest you please refer to the following section of documentation:

Aspose.Words Document Object Model

Best regards,

Hi Hafeez,

Thanks for your reply,

do you have any idea on OpenXml SDK… I am using openxml sdk. I am trying to add the comments in Word-doc(docx file). I am searching the text and trying to comment it. I am able to comment for paragraph which the text i am searching is exists in that paragraph. how to comment for that word not for full paragraph. Please find the below my code.

private void AddComments()
{
    int Count = 0; ;
    XmlDocument streamcom = UnPackDoc(@"D:\Test.docx", out Count);
    Count++;
    const string wordmlNamespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
    WordprocessingDocument wordDoc = WordprocessingDocument.Open(@"D:\Test.docx", true);
    MainDocumentPart docPart = wordDoc.MainDocumentPart;
    NameTable NameTble = new NameTable();
    XmlNamespaceManager nsManager = new XmlNamespaceManager(NameTble);
    nsManager.AddNamespace("w", wordmlNamespace);
    XmlDocument xdoc = new XmlDocument();
    xdoc.Load(docPart.GetStream());
    XmlNodeList comm = xdoc.SelectNodes("//w:p", nsManager);
    XmlNodeList rlist = xdoc.SelectNodes("//w:r", nsManager);
    XmlNodeList tlist = xdoc.SelectNodes("//w:t", nsManager);
    WordprocessingCommentsPart commentpart;
    NameTable NameTble2 = new NameTable();
    XmlNamespaceManager nsManager2 = new XmlNamespaceManager(NameTble2);
    nsManager.AddNamespace("w", wordmlNamespace);
    XmlDocument cmtDoc = new XmlDocument();
    if (docPart.WordprocessingCommentsPart == null)
    {
        commentpart = docPart.AddNewPart();
        cmtDoc = CreateCommentXmlFile();
    }
    else
    {
        commentpart = docPart.WordprocessingCommentsPart;
        cmtDoc = streamcom;
    }
    foreach (XmlNode rt in tlist)
    {
        if (rt.InnerText.ToUpper().Trim().Contains("would".ToUpper()) || rt.InnerText.ToUpper().Trim().Contains("will".ToUpper()))
        {
            XmlElement commentStartnode = xdoc.CreateElement("w:commentRangeStart", wordmlNamespace);
            XmlAttribute attr = commentStartnode.Attributes.Append(xdoc.CreateAttribute("w:id", wordmlNamespace));
            attr.Value = Count.ToString();
            XmlElement commentEndnode = xdoc.CreateElement("w:commentRangeEnd", wordmlNamespace);
            XmlAttribute attr1 = commentEndnode.Attributes.Append(xdoc.CreateAttribute("w:id", wordmlNamespace));
            attr1.Value = Count.ToString();
            XmlNode Prt = rt.ParentNode;
            Prt.InsertBefore(commentStartnode, rt);
            Prt.InsertAfter(commentEndnode, rt);
            XmlElement commentRefnode = xdoc.CreateElement("w:r", wordmlNamespace);
            XmlNode node2 = rt.ParentNode;
            node2.AppendChild(commentRefnode);
            XmlElement commentRefnode1 = xdoc.CreateElement("w:commentReference", wordmlNamespace);
            XmlAttribute attr2 = commentRefnode1.Attributes.Append(xdoc.CreateAttribute("w:id", wordmlNamespace));
            attr2.Value = Count.ToString();
            commentRefnode.AppendChild(commentRefnode1);
            XmlNode node1 = cmtDoc.SelectSingleNode("//w:comments", nsManager);
            XmlElement job = cmtDoc.CreateElement("w:comment", wordmlNamespace);
            XmlAttribute newAttribute = cmtDoc.CreateAttribute("w", "id", wordmlNamespace);
            newAttribute.InnerText = Count.ToString();
            job.Attributes.Append(newAttribute);
            node1.AppendChild(job);
            XmlElement job2 = cmtDoc.CreateElement("w:p", wordmlNamespace);
            job.AppendChild(job2);
            XmlElement cmtcmd = cmtDoc.CreateElement("w:r", wordmlNamespace);
            job2.AppendChild(cmtcmd);
            XmlElement cmtText = cmtDoc.CreateElement("w:t", wordmlNamespace);
            cmtText.InnerText = "Ram" + Count.ToString();
            cmtcmd.AppendChild(cmtText);
            Count++;
        }
    }
    StreamWriter commentpartWrt = new StreamWriter(commentpart.GetStream(FileMode.Create, FileAccess.Write));
    cmtDoc.Save(commentpartWrt);
    xdoc.Save(docPart.GetStream(FileMode.Create, FileAccess.Write));
    wordDoc.Close();
}

private XmlDocument UnPackDoc(string fileName, out int Index)
{
    Index = 0;
    XmlDocument doc = null;
    Stream comtstream = null;
    Package pkg = Package.Open(fileName);
    System.IO.FileInfo fi = new System.IO.FileInfo(fileName);
    string extension = fi.Extension.ToLower();
    // Get the embedded files names.
    foreach (PackagePart pkgPart in pkg.GetParts())
    {
        if (pkgPart.Uri.ToString() == "/word/comments.xml")
        {
            comtstream = pkgPart.GetStream();
            doc = new XmlDocument();
            doc.Load(comtstream);
            break;
        }
    }
    pkg.Close();
    const string wordmlNamespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
    NameTable NameTble = new NameTable();
    XmlNamespaceManager nsManager = new XmlNamespaceManager(NameTble);
    nsManager.AddNamespace("w", wordmlNamespace);
    if (doc != null)
    {
        XmlNodeList nlist = doc.SelectNodes("//w:comment", nsManager);
        int Large = 0;
        int Swap = 0;
        foreach (XmlNode node in nlist)
        {
            string str = node.Attributes.Item(0).InnerText;
            Swap = int.Parse(str);
            if (Swap > Large)
            {
                Large = Swap;
            }
            Index = Large;
        }
    }
    return doc;
}

even if we change the this if condition

if (rt.InnerText.ToUpper().Trim().Contains("would".ToUpper()) || rt.InnerText.ToUpper().Trim().Contains("will".ToUpper())) 

to

if(rt.InnerText.ToUpper().Trim()=="will") 

also it is commenting to full paragraph.

it would be great if you help on this.

Thanks,

Rambabu

Hi Rambabu,

Thanks for your inquiry. I am afraid, we only provide support for Aspose APIs.

Please check the following article to learn what are the benefits of using Aspose.Words for .NET over Open XML SDK:

Why not Open XML SDK

Best regards,

A post was split to a new topic: How do I add multiple comments (using loop) on specific locationHow do I add multiple comments (using loop) on specific location

A post was split to a new topic: Add comments to the specific text