Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ES-876618-Added sample for replace text in list paragraph #251

Open
wants to merge 14 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@


using Microsoft.VisualBasic.FileIO;
using Syncfusion.DocIO;
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;

namespace Replace_text_heading_paragraphs
Expand All @@ -10,24 +7,26 @@ class Program
{
static void Main(string[] args)
{
using (FileStream fileStreamPath = new FileStream(Path.GetFullPath(@"Data/Input.docx"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (FileStream inputFileStream = new FileStream(Path.GetFullPath(@"Data/Input.docx"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
//Opens an existing Word document.
using (WordDocument document = new WordDocument(fileStreamPath, FormatType.Automatic))
//Opens the input Word document.
using (WordDocument document = new WordDocument(inputFileStream, FormatType.Automatic))
{
for (int headingLevel = 1; headingLevel < 10; headingLevel++)
{
//Find headings based on the levels and endnote by paragraph in Word document.
List<Entity> headings = document.FindAllItemsByProperty(EntityType.Paragraph, "StyleName", "Heading " + headingLevel);
//Replace the headings with text.
//Iterate through all headings in the list.
for (int index = 0; index < headings.Count; index++)
{
//Cast the current heading to WParagraph.
WParagraph paragraph = headings[index] as WParagraph;
//Remove all child elements from the paragraph.
paragraph.ChildEntities.Clear();
paragraph.AppendText("Replaced Heading"+headingLevel+" text");
//Add new text to replace the heading content.
paragraph.AppendText("Replaced Heading" + headingLevel + " text");
}
}
//Creates file stream.
using (FileStream outputFileStream = new FileStream(Path.GetFullPath(@"Output/Result.docx"), FileMode.Create, FileAccess.ReadWrite))
{
//Saves the Word document to file stream.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.12.35309.182
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Replace-text-in-list-paragraph", "Replace-text-in-list-paragraph\Replace-text-in-list-paragraph.csproj", "{CD5449C2-95ED-4D2B-8984-E2D4386503BA}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{CD5449C2-95ED-4D2B-8984-E2D4386503BA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CD5449C2-95ED-4D2B-8984-E2D4386503BA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CD5449C2-95ED-4D2B-8984-E2D4386503BA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CD5449C2-95ED-4D2B-8984-E2D4386503BA}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {8AAB32F5-BB2E-4918-B6CC-FF84105D3AC3}
EndGlobalSection
EndGlobal
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<html>
<body>
<div style="font-family:calibri;color:#203864;">
<p>Road-150</p>
</div>
</body>
</html>
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
using Syncfusion.DocIO.DLS;
using Syncfusion.DocIO;

//Register Syncfusion license
Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("Mgo+DSMBMAY9C3t2UlhhQlNHfV5DQmBWfFN0QXNYfVRwdF9GYEwgOX1dQl9nSXZTc0VlWndfcXNSQWc=");

using (FileStream inputFileStream = new FileStream(Path.GetFullPath(@"Data/Template.docx"), FileMode.Open, FileAccess.ReadWrite))
{
//Open the template Word document.
using (WordDocument document = new WordDocument(inputFileStream, FormatType.Automatic))
{
string htmlFilePath = @"Data/File.html";
//Check if the HTML content is valid.
bool isvalidHTML = IsValidHTML(htmlFilePath);
if (isvalidHTML)
{
//Iterate through the sections in the document.
for (int i = 0; i < document.Sections.Count; i++)
{
//Iterate through the paragraphs within the section.
for (int j = 0; j < document.Sections[i].Paragraphs.Count; j++)
{
//Get the current paragraph from the section.
WParagraph paragraph = document.Sections[i].Paragraphs[j] as WParagraph;
//Define the variable containing the text to search within the paragraph.
string variable = "Mountain-300";
//If the paragraph contains the specific text, replace it with HTML content.
if (paragraph.Text.Contains(variable))
{
//Get the next sibling element of the current paragraph.
TextBodyItem nextSibling = paragraph.NextSibling as TextBodyItem;
//Get the index of the current paragraph within its parent text body.
int sourceIndex = paragraph.OwnerTextBody.ChildEntities.IndexOf(paragraph);
//Clear all child entities within the paragraph.
paragraph.ChildEntities.Clear();
//Get the list style name from the paragraph.
string listStyleName = paragraph.ListFormat.CurrentListStyle.Name;
//Get the current list level number.
int listLevelNum = paragraph.ListFormat.ListLevelNumber;
//Append HTML content from the specified file to the paragraph.
paragraph.AppendHTML(File.ReadAllText(Path.GetFullPath(htmlFilePath)));
//Reapply the original list style to the paragraph.
paragraph.ListFormat.ApplyStyle(listStyleName);
//Reapply the original list level number.
paragraph.ListFormat.ListLevelNumber = listLevelNum;
//Determine the index of the next sibling if it exists.
int nextSiblingIndex = nextSibling != null ? nextSibling.OwnerTextBody.ChildEntities.IndexOf(nextSibling) : -1;
//Apply the same list style to newly added paragraphs from the HTML content.
for (int k = sourceIndex; k < paragraph.OwnerTextBody.Count; k++)
{
//Stop applying the style if the next sibling is reached.
if (nextSiblingIndex != -1 && k == nextSiblingIndex)
{
break;
}
Entity entity = paragraph.OwnerTextBody.ChildEntities[k];
//Apply the list style only if the entity is a paragraph.
if (entity is WParagraph)
{
(entity as WParagraph).ListFormat.ApplyStyle(listStyleName);
}
else
{
break;
}
}
}
}
}
}
using (FileStream outputFileStream = new FileStream(Path.GetFullPath(@"Output/Result.docx"), FileMode.Create, FileAccess.ReadWrite))
{
//Save the modified Word document to the output file stream.
document.Save(outputFileStream, FormatType.Docx);
}
}
}

/// <summary>
/// Validates whether the HTML content from the specified file is well-formed XHTML.
/// </summary>
static bool IsValidHTML(string htmlFilePath)
{
using (WordDocument document = new WordDocument())
{
//Add a section for the HTML content.
IWSection section = document.AddSection();
//Read the HTML string from the specified file.
string htmlString = File.ReadAllText(Path.GetFullPath(htmlFilePath));
//Validate the HTML string.
return section.Body.IsValidXHTML(htmlString, XHTMLValidationType.None);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>Replace_text_in_list_paragraph</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Syncfusion.DocIO.Net.Core" Version="*" />
</ItemGroup>

<ItemGroup>
<None Update="Data\File.html">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Data\Template.docx">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Output\.gitkeep">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>

</Project>
25 changes: 25 additions & 0 deletions Tables/Find-table-and-add-row/Find-table-and-add-row.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.12.35309.182
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Find-table-and-add-row", "Find-table-and-add-row\Find-table-and-add-row.csproj", "{E8C23293-ABC9-4C54-81BA-9C5FBA6D85C1}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{E8C23293-ABC9-4C54-81BA-9C5FBA6D85C1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E8C23293-ABC9-4C54-81BA-9C5FBA6D85C1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E8C23293-ABC9-4C54-81BA-9C5FBA6D85C1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E8C23293-ABC9-4C54-81BA-9C5FBA6D85C1}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {EC6BCFD8-E759-47DE-BC97-AC492B3D6DF8}
EndGlobalSection
EndGlobal
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>Find_table_and_add_row</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Syncfusion.DocIO.Net.Core" Version="*" />
</ItemGroup>

<ItemGroup>
<None Update="Data\Template.docx">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Output\.gitkeep">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>

</Project>
28 changes: 28 additions & 0 deletions Tables/Find-table-and-add-row/Find-table-and-add-row/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;


//Register Syncfusion license
Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("Mgo+DSMBMAY9C3t2UlhhQlNHfV5DQmBWfFN0QXNYfVRwdF9GYEwgOX1dQl9nSXZTc0VlWndfcXNSQWc=");

using (FileStream inputFileStream = new FileStream(Path.GetFullPath("Data/Template.docx"), FileMode.Open, FileAccess.ReadWrite))
{
// Open the input Word document
using (WordDocument document = new WordDocument(inputFileStream, FormatType.Docx))
{
// Find a table with its alternate text (Title property).
WTable table = document.FindItemByProperty(EntityType.Table, "Title", "DataTable") as WTable;
// Check if the table exists.
if (table != null)
{
// Add a new row to the table.
table.AddRow();
}

using (FileStream outputFileStream = new FileStream(Path.GetFullPath("Output/Result.docx"), FileMode.Create, FileAccess.Write))
{
// Save the modified document to the output file stream.
document.Save(outputFileStream, FormatType.Docx);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.12.35309.182
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Replace-row-with-multiple-rows", "Replace-row-with-multiple-rows\Replace-row-with-multiple-rows.csproj", "{7D07A56C-8B23-4CFE-9E8C-903C5C1EF6CB}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{7D07A56C-8B23-4CFE-9E8C-903C5C1EF6CB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7D07A56C-8B23-4CFE-9E8C-903C5C1EF6CB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7D07A56C-8B23-4CFE-9E8C-903C5C1EF6CB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7D07A56C-8B23-4CFE-9E8C-903C5C1EF6CB}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {F9812314-7D24-42E7-8090-5B2969EB47E9}
EndGlobalSection
EndGlobal
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

Loading