Articles in this section
Category / Section

How to Restart Number when Replacing Text with HTML in .Net Core Word?

12 mins read

Syncfusion® Essential® DocIO is a .NET Word library used to create, read, edit, and convert Word documents programmatically without Microsoft Word or interop dependencies. Using this library, you can restart numbering when replacing multiple texts with the same HTML list in a Word document using C#.

To achieve this requirement, you can follow the steps below:

  • Open the template and replacement (HTML) document.
  • Find the text to be replaced and wrap it with a bookmark.
  • Replace the text with the HTML content and extract the updated content.
  • Store and update list numbering.

Steps to restart numbering when replacing multiple texts with the same HTML list in a Word document:

  1. Create a new .NET Core console application project.
    Create console application in Visual Studio
  2. Install the Syncfusion.DocIO.Net.Core NuGet package as a reference to your project from NuGet.org.
    Add DocIO NuGet package reference to the project

Starting with v16.2.0.x, if you reference Syncfusion® assemblies from trial setup or from the NuGet feed, include a license key in your projects. Refer to the link to learn about generating and registering a Syncfusion® license key in your application to use the components without a trial message.

  1. Include the following namespaces in the Program.cs file
    C#
using Syncfusion.DocIO.DLS;
using Syncfusion.DocIO; 
  1. Use the following code example to store the names of different list styles used in the document.
    C#
// List to store the names of different list styles used in the document.
static List<string> listStyleNames = new List<string>();
  1. Use the following code example to restart numbering when replacing multiple texts with the same HTML list in a Word document.
    C#
// Load the input Word document from file stream
using (FileStream docStream = new FileStream(Path.GetFullPath(@"Data/Template.docx"), FileMode.Open, FileAccess.Read))
{
    // Open the Word document
    using (WordDocument document = new WordDocument(docStream, FormatType.Docx))
    {
        // Load the input Word document from file stream
        using (FileStream htmlStream = new FileStream(Path.GetFullPath(@"Data/sample.html"), FileMode.Open, FileAccess.Read))
        {
            // Open the Word document
            using (WordDocument replaceDoc = new WordDocument(htmlStream, FormatType.Html))
            {
                //Replace the first word with HTML file content
                ReplaceText(document, "Tag1", replaceDoc, true);
                //Replace the second word with HTML file content
                ReplaceText(document, "Tag2", replaceDoc, false);
                // Save the modified document to a new file
                using (FileStream docStream1 = new FileStream(Path.GetFullPath(@"Output/Result.docx"), FileMode.Create, FileAccess.Write))
                {
                    document.Save(docStream1, FormatType.Docx);
                }
            }
        }
    }
}
  1. Use the following code example to add a bookmark start before the found text range and bookmark end after it.
    C#
private static void ReplaceText(WordDocument document, string findText, WordDocument replaceDoc, bool isFirstReplace)
{
   TextSelection selection = document.Find(findText, true, true);
   if (selection != null)
   {
       //Get the textrange
       WTextRange textRange = selection.GetAsOneRange();
       //Get the owner paragraph
       WParagraph ownerPara = textRange.OwnerParagraph;

       //For first time replacement alone.
       if (isFirstReplace)
       {
           //Get the index of the textrange
           int index = ownerPara.ChildEntities.IndexOf(textRange);
           //Add the bookmark start before the textrange
           BookmarkStart bookmarkStart = new BookmarkStart(document, "Bkmk");
           ownerPara.ChildEntities.Insert(index, bookmarkStart);
           //Increment the index
           index++;
           //Add the bookmark end after the textrange
           BookmarkEnd bookmarkEnd = new BookmarkEnd(document, "Bkmk");
           ownerPara.ChildEntities.Insert(index + 1, bookmarkEnd);
           //Replace the text with HTML content
           document.Replace(findText, replaceDoc, true, true);
           //Navigate to the bookmark content
           BookmarksNavigator navigator = new BookmarksNavigator(document);
           navigator.MoveToBookmark("Bkmk");
           //Get the bookmark content
           TextBodyPart bodyPart = navigator.GetBookmarkContent();
           //Get the list of list styles
           GetListStyleName(bodyPart.BodyItems);
           //Remove the bookmark
           Bookmark bookmark = document.Bookmarks.FindByName("Bkmk");
           document.Bookmarks.Remove(bookmark);
       }
       else
       {
           //Get the next sibling of the owner paragraph
           IEntity nextSibling = ownerPara.NextSibling;
           //Get the owner paragraph index as start index 
           int startIndex = ownerPara.OwnerTextBody.ChildEntities.IndexOf(ownerPara);
           //Replace the text with HTML content
           document.Replace(findText, replaceDoc, true, true);
           //Get the end index
           //If the next sibling is present then it is the end index, else the child entities count
           int endIndex = nextSibling != null ? ownerPara.OwnerTextBody.ChildEntities.IndexOf(nextSibling)
               : ownerPara.OwnerTextBody.ChildEntities.Count;
           //Restart the numbering
           RestartNumbering(startIndex, endIndex, document.Sections[0].Body.ChildEntities);
       }
   }
}
  1. Use the following code example to get the list style names from the collection.
    C#
private static void GetListStyleName(EntityCollection collection)
{
    //Iterate through the collection
    foreach (Entity entity in collection)
    {
        switch (entity.EntityType)
        {
            //Entity is paragraph
            case EntityType.Paragraph:
                WParagraph wParagraph = (WParagraph)entity;
                //Check whether the paragraph has list format with numbered type which is not in the collection list.
                if (wParagraph.ListFormat.CurrentListLevel != null
                    && wParagraph.ListFormat.ListType == ListType.Numbered
                    && !listStyleNames.Contains(wParagraph.ListFormat.CurrentListStyle.Name))
                    //Add the list style name to the collection list
                    listStyleNames.Add(wParagraph.ListFormat.CurrentListStyle.Name);
                break;
            //Entity is Table
            case EntityType.Table:
                WTable table = (WTable)entity;
                //Iterate through rows
                foreach (WTableRow row in table.Rows)
                {
                    //Iterate through cells
                    foreach (WTableCell cell in row.Cells)
                    {
                        //Get the list style name
                        GetListStyleName(cell.ChildEntities);
                    }
                }
                break;
        }
    }
}
  1. Use the following code example to restart the numbering for replaced items.
    C#
private static void RestartNumbering(int startIndex, int endIndex, EntityCollection collection)
{
   //Local value
   string listName = string.Empty;
   for (int i = startIndex; i < endIndex; i++)
   {
       Entity entity = collection[i];
       switch (entity.EntityType)
       {
           //Entity is Paragraph
           case EntityType.Paragraph:
               WParagraph wParagraph = (WParagraph)entity;
               //Check whether the paragraph has current list level and the same list name in the collection list.
               if (wParagraph.ListFormat.CurrentListLevel != null
                   && listStyleNames.Contains(wParagraph.ListFormat.CurrentListStyle.Name))
               {
                   //If the local name is not equal to current list name, then restart the numbering
                   if (listName != wParagraph.ListFormat.CurrentListStyle.Name)
                   {
                       //Set the current list name as local name
                       listName = wParagraph.ListFormat.CurrentListStyle.Name;
                       //Enable restart numbering
                       wParagraph.ListFormat.RestartNumbering = true;
                   }
                   //If the local name and current list name are equal, then continue list numbering
                   else
                       wParagraph.ListFormat.ContinueListNumbering();
               }
               break;
           //Entity is table
           case EntityType.Table:
               WTable table = (WTable)entity;
               //Iterate through rows
               foreach (WTableRow row in table.Rows)
               {
                   //Iterate through cells
                   foreach (WTableCell cell in row.Cells)
                   {
                       //Restart numbering for child entities in the cell.
                       RestartNumbering(0, cell.ChildEntities.Count, cell.ChildEntities);
                   }
               }
               break;
       }
   }
}

You can download a complete working sample to restart numbering when replacing multiple texts with the same HTML list in a Word document from the GitHub.

Output Word document

Take a moment to peruse the documentation where you can find basic Word document processing options along with the features like mail merge, merge, split, and compare Word documents, find and replace text in the Word document, protect the Word documents, and most importantly, the PDF and Image conversions with code examples.

Conclusion

I hope you enjoyed learning about how to restart number when replacing text with HTML in .Net Core Word.

You can refer to our ASP.NET Core DocIO feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our ASP.NET Core DocIO example to understand how to create and manipulate data.

For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion®, you can try our 30-day free trial to check out our other controls.

If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied