How to replace text between custom tags using bookmarks in a Word document
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 replace text between custom tags using bookmarks in a Word document using C#.
To achieve this, follow the steps below:
- Retrieve the content between the tags in the source document as a body part.
- Find the start tag in the destination document and add a bookmark after the start tag.
- Find the end tag in the destination document and add a bookmark before the end tag.
- Replace the bookmark content in the destination document with the body part from the source document.
- Remove the bookmark from the destination document after replacing the content.
Steps to replace text between custom tags using bookmarks in a Word document:
- Create a new .NET Core console application project.
- Install the Syncfusion.DocIO.Net.Core NuGet package as a reference to your project from NuGet.org.
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 trail message.
- Include the following namespaces in Program.cs file
C#
using Syncfusion.DocIO.DLS;
using Syncfusion.DocIO;
using System.Text.RegularExpressions;
using System.IO;
- Use the following code example to replace text between custom tags using bookmarks in a Word document.
C#
using (FileStream fileStreamPath = new FileStream(Path.GetFullPath(@"Data/DestinationDocument.docx"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
//Open the destination Word document.
using (WordDocument destinationDocument = new WordDocument(fileStreamPath, FormatType.Docx))
{
using (FileStream sourceFileStream = new FileStream(Path.GetFullPath(@"Data/SourceDocument.docx"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
//Open the source Word document.
using (WordDocument sourceDocument = new WordDocument(sourceFileStream, FormatType.Docx))
{
//Get the content between the tags in the source document as body part.
TextSelection[] textSelections = sourceDocument.FindSingleLine(new Regex("<SourceTag>(.*)</SourceTag>"));
if (textSelections != null)
{
TextBodyPart bodyPart = new TextBodyPart(destinationDocument);
for (int i = 1; i < textSelections.Length - 1; i++)
{
WParagraph paragraph = new WParagraph(destinationDocument);
foreach (var range in textSelections[i].GetRanges())
{
WTextRange textrange = range.Clone() as WTextRange;
paragraph.ChildEntities.Add(textrange);
}
bodyPart.BodyItems.Add(paragraph);
}
//Replace the text between specified tags in the destination document using a bookmark
//with the content from the source document.
ReplaceTextBetweenTags(destinationDocument, bodyPart);
}
//Create file stream.
using (FileStream outputFileStream = new FileStream(Path.GetFullPath(@"Output/Output.docx"), FileMode.Create, FileAccess.ReadWrite))
{
//Save the Word document to file stream.
destinationDocument.Save(outputFileStream, FormatType.Docx);
}
}
}
}
}
- Use the following helper method to replace the text between specified tags in the destination document using a bookmark with the content from the source document.
C#
/// <summary>
/// Replaces the content between specified start and end tags within the destination document using a bookmark.
/// </summary>
private static void ReplaceTextBetweenTags(WordDocument destinationDocument, TextBodyPart bodyPart)
{
//Define the start and end tags to identify the content to be replaced.
string startTag = "<DestTag>";
string endTag = "</DestTag>";
//Create bookmark start and bookmark end.
BookmarkStart bookmarkStart = new BookmarkStart(destinationDocument, "Adventure_Bkmk");
BookmarkEnd bookmarkEnd = new BookmarkEnd(destinationDocument, "Adventure_Bkmk");
//Find the start tag in the destination document.
TextSelection textSelection = destinationDocument.Find(startTag, false, false);
if (textSelection == null) return; //Exit if start tag is not found.
//Add a bookmark start after the start tag location.
WTextRange startTagTextRange = textSelection.GetAsOneRange();
WParagraph startTagParagraph = startTagTextRange.OwnerParagraph;
int startTagIndex = startTagParagraph.ChildEntities.IndexOf(startTagTextRange);
startTagParagraph.Items.Insert(startTagIndex + 1, bookmarkStart);
//Find the end tag in the destination document.
textSelection = destinationDocument.Find(endTag, false, false);
if (textSelection == null) return; // Exit if end tag is not found
//Add a bookmark end at the end tag location (before end tag).
WTextRange endTagTextRange = textSelection.GetAsOneRange();
WParagraph endTagParagraph = endTagTextRange.OwnerParagraph;
int endTagIndex = endTagParagraph.ChildEntities.IndexOf(endTagTextRange);
endTagParagraph.Items.Insert(endTagIndex, bookmarkEnd);
//Create the bookmark navigator instance to access the bookmark.
BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(destinationDocument);
//Move the virtual cursor to the location of the bookmark "Adventure_Bkmk".
bookmarkNavigator.MoveToBookmark("Adventure_Bkmk");
//Replace the bookmark content with body part.
bookmarkNavigator.ReplaceBookmarkContent(bodyPart);
//Remove the bookmark from the destination document after replacing the content.
Bookmark bookmark = destinationDocument.Bookmarks.FindByName("Adventure_Bkmk");
if (bookmark != null)
destinationDocument.Bookmarks.Remove(bookmark);
}
You can download a complete working sample to replace text between custom tags using bookmarks in a Word document from the GitHub.
The input documents are as follows.
By executing the program, you will get the Word document as follows.
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 how to replace the table cell content in .NET Core Word document.
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!