Skip to content

Commit c2553fe

Browse files
Added sample to replace text between custom tags using bookmarks
1 parent 9f2d2d7 commit c2553fe

File tree

6 files changed

+152
-0
lines changed

6 files changed

+152
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
2+
Microsoft Visual Studio Solution File, Format Version 12.00
3+
# Visual Studio Version 16
4+
VisualStudioVersion = 16.0.31911.196
5+
MinimumVisualStudioVersion = 10.0.40219.1
6+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Replace-text-inside-tag", "Replace-text-inside-tag\Replace-text-inside-tag.csproj", "{C17B90BC-F559-456B-B189-90B53FF6CDD4}"
7+
EndProject
8+
Global
9+
GlobalSection(SolutionConfigurationPlatforms) = preSolution
10+
Debug|Any CPU = Debug|Any CPU
11+
Release|Any CPU = Release|Any CPU
12+
EndGlobalSection
13+
GlobalSection(ProjectConfigurationPlatforms) = postSolution
14+
{C17B90BC-F559-456B-B189-90B53FF6CDD4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15+
{C17B90BC-F559-456B-B189-90B53FF6CDD4}.Debug|Any CPU.Build.0 = Debug|Any CPU
16+
{C17B90BC-F559-456B-B189-90B53FF6CDD4}.Release|Any CPU.ActiveCfg = Release|Any CPU
17+
{C17B90BC-F559-456B-B189-90B53FF6CDD4}.Release|Any CPU.Build.0 = Release|Any CPU
18+
EndGlobalSection
19+
GlobalSection(SolutionProperties) = preSolution
20+
HideSolutionNode = FALSE
21+
EndGlobalSection
22+
GlobalSection(ExtensibilityGlobals) = postSolution
23+
SolutionGuid = {EF357FC6-E9E5-4E3C-B932-43F727BE1DE4}
24+
EndGlobalSection
25+
EndGlobal
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
using Syncfusion.DocIO;
2+
using Syncfusion.DocIO.DLS;
3+
using System.IO;
4+
using System.Text.RegularExpressions;
5+
6+
namespace Replace_text_inside_tag
7+
{
8+
class Program
9+
{
10+
static void Main(string[] args)
11+
{
12+
using (FileStream fileStreamPath = new FileStream(Path.GetFullPath(@"Data/DestinationDocument.docx"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
13+
{
14+
//Open the destination Word document.
15+
using (WordDocument destinationDocument = new WordDocument(fileStreamPath, FormatType.Docx))
16+
{
17+
using (FileStream sourceFileStream = new FileStream(Path.GetFullPath(@"Data/SourceDocument.docx"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
18+
{
19+
//Open the source Word document.
20+
using (WordDocument sourceDocument = new WordDocument(sourceFileStream, FormatType.Docx))
21+
{
22+
//Get the content between the tags in the source document as body part.
23+
TextSelection[] textSelections = sourceDocument.FindSingleLine(new Regex("<SourceTag>(.*)</SourceTag>"));
24+
if (textSelections != null)
25+
{
26+
TextBodyPart bodyPart = new TextBodyPart(destinationDocument);
27+
for (int i = 1; i < textSelections.Length - 1; i++)
28+
{
29+
WParagraph paragraph = new WParagraph(destinationDocument);
30+
foreach (var range in textSelections[i].GetRanges())
31+
{
32+
WTextRange textrange = range.Clone() as WTextRange;
33+
paragraph.ChildEntities.Add(textrange);
34+
}
35+
bodyPart.BodyItems.Add(paragraph);
36+
}
37+
//Replace the text between specified tags in the destination document using a bookmark
38+
//with the content from the source document.
39+
ReplaceTextBetweenTags(destinationDocument, bodyPart);
40+
}
41+
//Create file stream.
42+
using (FileStream outputFileStream = new FileStream(Path.GetFullPath(@"Output/Output.docx"), FileMode.Create, FileAccess.ReadWrite))
43+
{
44+
//Save the Word document to file stream.
45+
destinationDocument.Save(outputFileStream, FormatType.Docx);
46+
}
47+
}
48+
}
49+
}
50+
}
51+
}
52+
#region Helper Methods
53+
/// <summary>
54+
/// Replaces the content between specified start and end tags within the destination document using a bookmark.
55+
/// </summary>
56+
/// <param name="destinationDocument">The Word document where the replacement is to be performed.</param>
57+
/// <param name="bodyPart">The content to insert between the specified start and end tags.</param>
58+
private static void ReplaceTextBetweenTags(WordDocument destinationDocument, TextBodyPart bodyPart)
59+
{
60+
//Define the start and end tags to identify the content to be replaced.
61+
string startTag = "<DestTag>";
62+
string endTag = "</DestTag>";
63+
//Create bookmark start and bookmark end.
64+
BookmarkStart bookmarkStart = new BookmarkStart(destinationDocument, "Adventure_Bkmk");
65+
BookmarkEnd bookmarkEnd = new BookmarkEnd(destinationDocument, "Adventure_Bkmk");
66+
67+
//Find the start tag in the destination document.
68+
TextSelection textSelection = destinationDocument.Find(startTag, false, false);
69+
if (textSelection == null) return; //Exit if start tag is not found.
70+
71+
//Add a bookmark start after the start tag location.
72+
WTextRange startTagTextRange = textSelection.GetAsOneRange();
73+
WParagraph startTagParagraph = startTagTextRange.OwnerParagraph;
74+
int startTagIndex = startTagParagraph.ChildEntities.IndexOf(startTagTextRange);
75+
startTagParagraph.Items.Insert(startTagIndex + 1, bookmarkStart);
76+
77+
//Find the end tag in the destination document.
78+
textSelection = destinationDocument.Find(endTag, false, false);
79+
if (textSelection == null) return; // Exit if end tag is not found
80+
81+
//Add a bookmark end at the end tag location (before end tag).
82+
WTextRange endTagTextRange = textSelection.GetAsOneRange();
83+
WParagraph endTagParagraph = endTagTextRange.OwnerParagraph;
84+
int endTagIndex = endTagParagraph.ChildEntities.IndexOf(endTagTextRange);
85+
endTagParagraph.Items.Insert(endTagIndex, bookmarkEnd);
86+
87+
//Create the bookmark navigator instance to access the bookmark.
88+
BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(destinationDocument);
89+
//Move the virtual cursor to the location of the bookmark "Adventure_Bkmk".
90+
bookmarkNavigator.MoveToBookmark("Adventure_Bkmk");
91+
//Replace the bookmark content with body part.
92+
bookmarkNavigator.ReplaceBookmarkContent(bodyPart);
93+
94+
//Remove the bookmark from the destination document after replacing the content.
95+
Bookmark bookmark = destinationDocument.Bookmarks.FindByName("Adventure_Bkmk");
96+
if (bookmark != null)
97+
destinationDocument.Bookmarks.Remove(bookmark);
98+
}
99+
#endregion
100+
}
101+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<TargetFramework>net8.0</TargetFramework>
6+
<RootNamespace>Replace_text_inside_tag</RootNamespace>
7+
</PropertyGroup>
8+
9+
<ItemGroup>
10+
<PackageReference Include="Syncfusion.DocIO.Net.Core" Version="*" />
11+
</ItemGroup>
12+
13+
<ItemGroup>
14+
<None Update="Data\DestinationDocument.docx">
15+
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
16+
</None>
17+
<None Update="Data\SourceDocument.docx">
18+
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
19+
</None>
20+
<None Update="Output\.gitkeep">
21+
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
22+
</None>
23+
</ItemGroup>
24+
25+
</Project>

0 commit comments

Comments
 (0)