How to maintain list format of the source document to destination document after replacing bookmark content
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 maintain list format of the source document to destination document after replacing bookmark content using C#.
When replacing bookmark content in a Word document using the ReplaceContent method, the list format from the destination document is not applied to the replaced content. Instead, the replaced content retains the formatting from the source document. To maintain the list format from the destination document, you can retrieve the paragraph containing the replaced content after the replacement and apply the appropriate list formatting.
Steps to maintain list format of the source document to destination document after replacing bookmark content:
- 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;
- Use the following code example to maintain list format of the source document to destination document after replacing bookmark content.
C#
using (FileStream destinationStream = new FileStream(Path.GetFullPath("Data/DestinationDocument.docx"), FileMode.Open, FileAccess.Read))
{
//Open the destination Word document.
using (WordDocument destinationDocument = new WordDocument(destinationStream, FormatType.Docx))
{
using (FileStream srcStream = new FileStream(Path.GetFullPath(@"Data/SourceDocument.docx"), FileMode.Open, FileAccess.Read))
{
//Open the source Word document.
using (WordDocument srcDocument = new WordDocument(srcStream, FormatType.Docx))
{
//Replace text "Text one" in the destination document with content from the bookmark "bkmk1" in the source document.
ReplaceTextAndMaintainListFormat(destinationDocument, srcDocument, "Text one", "bkmk1");
//Replace text "Text two" in the destination document with content from the bookmark "bkmk2" in the source document.
ReplaceTextAndMaintainListFormat(destinationDocument, srcDocument, "Text two", "bkmk2");
//Save the modified destination document to the output stream.
using (FileStream output = new FileStream(Path.GetFullPath("Output/Output.docx"), FileMode.Create, FileAccess.Write))
{
destinationDocument.Save(output, FormatType.Docx);
}
}
}
}
}
- Use the following helper method to replace text in a Word document with bookmark content from another document.
C#
/// <summary>
/// Replaces specific text in a Word document with bookmarked content from another document, maintaining formatting.
/// </summary>
private static void ReplaceTextAndMaintainListFormat(WordDocument destinationDocument, WordDocument sourceDocument, string tokenToFind, string textBookmark)
{
string bookmarkRef = textBookmark + "_bm";
// Find the text in the destination document where the bookmark start needs to be inserted.
TextSelection start = destinationDocument.Find(tokenToFind, true, true);
if (start != null)
{
// Get the selected text range and its parent paragraph.
WTextRange startText = start.GetAsOneRange();
WParagraph startParagraph = startText.OwnerParagraph;
// Get the index of the selected text range in the paragraph.
int index = startParagraph.Items.IndexOf(startText);
// Remove the selected text at the identified index.
startParagraph.Items.Remove(startText);
// Create a BookmarkStart with a unique reference and insert it at the same index.
BookmarkStart bookmarkStart = new BookmarkStart(destinationDocument, bookmarkRef);
startParagraph.Items.Insert(index, bookmarkStart);
// Append a BookmarkEnd with the same reference to mark the bookmarkâs end.
startParagraph.AppendBookmarkEnd(bookmarkRef);
// Check if the specified bookmark exists in the source document.
if (sourceDocument.Bookmarks.FindByName(textBookmark) != null)
{
// Move the navigator to the bookmark in the source document.
BookmarksNavigator bookmarksNavigator = new BookmarksNavigator(sourceDocument);
bookmarksNavigator.MoveToBookmark(textBookmark);
// Extract the content within the bookmark.
WordDocumentPart wordDocumentPart = bookmarksNavigator.GetContent();
// Move the navigator to the newly created bookmark in the destination document.
bookmarksNavigator = new BookmarksNavigator(destinationDocument);
bookmarksNavigator.MoveToBookmark(bookmarkRef);
// Get the paragraph containing the bookmark start in the destination document.
WParagraph destinationPara = bookmarksNavigator.CurrentBookmark.BookmarkStart.OwnerParagraph;
// Store the list style, first-line indent, and left indent of the paragraph.
string listStyleName = destinationPara.ListFormat.CustomStyleName;
float firstLineIndent = destinationPara.ParagraphFormat.FirstLineIndent;
float leftIndent = destinationPara.ParagraphFormat.LeftIndent;
// Replace the bookmark content with the extracted content from the source document.
bookmarksNavigator.ReplaceContent(wordDocumentPart);
// Reapply the original list style and indent settings to the paragraph.
destinationPara.ListFormat.ApplyStyle(listStyleName);
destinationPara.ParagraphFormat.FirstLineIndent = firstLineIndent;
destinationPara.ParagraphFormat.LeftIndent = leftIndent;
}
else
{
// If the bookmark is not found, replace the content with an empty string.
BookmarksNavigator bookmarksNavigator = new BookmarksNavigator(destinationDocument);
bookmarksNavigator.MoveToBookmark(bookmarkRef);
bookmarksNavigator.ReplaceBookmarkContent(string.Empty, true);
}
}
}
You can download a complete working sample to maintain list format of the source document to destination document after replacing bookmark content 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 about how to maintain list format of the source document to destination document after replacing bookmark content.
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!