Articles in this section
Category / Section

How to replace text within bookmark content in Word document?

3 mins read

Syncfusion Essential DocIO is a .NET Core Word library used to create, read, and edit Word documents programmatically without Microsoft Word or Interop dependencies. Using this library, you can replace a particular text within bookmark in the Word document in C#.

Steps to replace a text within bookmark content in the Word document:

  1. Create a new C# .NET Core console application project. Create .NET Core console application in Visual Studio in ASP.NET Core Word
  2. Install the Syncfusion.DocIO.Net.Core NuGet package as a reference to your .NET Core applications from NuGet.org. Add DocIO.Net.Core NuGet packages of ASP.NET Core Word
  3. Include the following namespace in the Program.cs file:

C#

using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
  1. Use the following code example to replace a text within bookmark content in the Word document.

C#

//Open the file as a stream.
using (FileStream inputStream = new FileStream(Path.GetFullPath(@"../../../Input.docx"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
    //Load the file stream into a Word document.
    using (WordDocument document = new WordDocument(inputStream, FormatType.Docx))
    {
        //Replace a text within the bookmark.
        ReplaceBookmarkText(document, "Description", "Price", "Amount");
        ReplaceBookmarkText(document, "Address", "290", "two hundred and ninety");
        //Create a file stream.
        using (FileStream outputFileStream = new FileStream(Path.GetFullPath(@"../../../Sample.docx"), FileMode.Create, FileAccess.ReadWrite))
        {
            //Save the Word document to the file stream.
            document.Save(outputFileStream, FormatType.Docx);
            }
        }
}
  1. The following code example shows ReplaceBookmarkText method which is used to replace a text within a bookmark content.

C#

public static void ReplaceBookmarkText(WordDocument document, string bookmarkName, string textToFind, string textToReplace)
{
     //Check whether the bookmark name is valid.
    if (string.IsNullOrEmpty(bookmarkName) || document.Bookmarks.FindByName(bookmarkName) == null)
        return;
    //Move to the virtual cursor before the bookmark end location of the bookmark.
    BookmarksNavigator bookmarksNavigator = new BookmarksNavigator(document);
    bookmarksNavigator.MoveToBookmark(bookmarkName);
    //Replace the bookmark content with new text.
    TextBodyPart textBodyPart = bookmarksNavigator.GetBookmarkContent();
    //Get paragraph from the textBody part.
    foreach (TextBodyItem item in textBodyPart.BodyItems)
    {
        IterateTextBody(item, textToFind, textToReplace);
    }
    //Replace the bookmark content with text body part.
    bookmarksNavigator.ReplaceBookmarkContent(textBodyPart);
}
  1. The following code example shows IterateTextBody method which is used to iterate text body elements.

C#

public static void IterateTextBody(TextBodyItem item, string textToFind, string textToReplace)
{
    switch (item.EntityType)
    {
        case EntityType.Paragraph:
                WParagraph paragraph = (WParagraph)item;
                 //Replace a text in the bookmark content.
                 paragraph.Replace(new System.Text.RegularExpressions.Regex(textToFind), textToReplace);
                 break;
        case EntityType.Table:
                WTable table = (WTable)item;
                foreach (WTableRow row in table.Rows)
                {
                    foreach (WTableCell cell in row.Cells)
                    {
                        foreach (TextBodyItem bodyItem in cell.ChildEntities)
                        {
                            IterateTextBody(bodyItem, textToFind, textToReplace);
                        }
                    }
                }
                break;
                case EntityType.BlockContentControl:
                        WTextBody body = (item as IBlockContentControl).TextBody;
                        foreach (TextBodyItem bodyitem in body.ChildEntities)
                        IterateTextBody(bodyitem, textToFind, textToReplace);
                        break;
            }
}

A complete working sample to replace a text within a bookmark content in the Word document in C# can be downloaded from GitHub.

By executing the program, you will get the Output document as follows.

Output document generated in ASP.NET Core Word

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

Explore more about the rich set of Syncfusion Word Framework features.

See Also:

How to replace the particular text with hyperlink in Word document

How to find the empty paragraphs in the Word document using Essential DocIO

How to replace text in a Word document with HTML

How to find and replace text inside table in Word document

How to find and replace text in headers and footers of Word document

How to find and replace placeholder with page break in Word document

How to find and replace text with content control in Word document?

How to find and replace line break in Word document as paragraph mark?

Note:

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 link to learn about generating and registering Syncfusion license key in your application to use the components without trail message.

 

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