Articles in this section
Category / Section

How to replace text within a bookmark content in a 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 particular text within a bookmark in a Word document in C#.

Steps to replace a text within a bookmark content in a 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 namespaces in the Program.cs file:

C#

using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
  1. Use the following code example to replace text within bookmark content in a 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 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 the ReplaceBookmarkText method, which is used to replace text within 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 textBodyPart.
    foreach (TextBodyItem item in textBodyPart.BodyItems)
    {
        IterateTextBody(item, textToFind, textToReplace);
    }
    // Replace the bookmark content with the text body part.
    bookmarksNavigator.ReplaceBookmarkContent(textBodyPart);
}
  1. The following code example shows the 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 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 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 features like mail mergemerge and split documents, find and replace text in the Word document, protect the Word documents, and most importantly, 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 a hyperlink in the Word document

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

How to replace text in a Word document with HTML

How to find and replace text inside a table in the Word document

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

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

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

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

Note:

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

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