Skip to content

Commit c90373b

Browse files
Merge pull request #475 from SyncfusionExamples/985218-video
985218 - How to Create an IF Field in a Word Document Using the .NET Word Library
2 parents a0ef46e + 522ea3a commit c90373b

File tree

77 files changed

+74990
-0
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

77 files changed

+74990
-0
lines changed
Lines changed: 220 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,220 @@
1+
using System.Diagnostics;
2+
using Create_IF_Field.Models;
3+
using Microsoft.AspNetCore.Mvc;
4+
using Syncfusion.DocIO;
5+
using Syncfusion.DocIO.DLS;
6+
7+
namespace Create_IF_Field.Controllers
8+
{
9+
public class HomeController : Controller
10+
{
11+
private readonly ILogger<HomeController> _logger;
12+
13+
public HomeController(ILogger<HomeController> logger)
14+
{
15+
_logger = logger;
16+
}
17+
18+
public IActionResult SimpleIfField()
19+
{
20+
// Create a new Word document
21+
WordDocument document = new WordDocument();
22+
23+
// Add a section and a title
24+
document.EnsureMinimal();
25+
IWParagraph titleParagraph = document.LastSection.AddParagraph();
26+
titleParagraph.AppendText("Student Grade Evaluation Report");
27+
titleParagraph.ApplyStyle(BuiltinStyle.Heading1);
28+
titleParagraph.ParagraphFormat.LineSpacing = 18f;
29+
30+
// Add introductory explanation
31+
IWParagraph introParagraph = document.LastSection.AddParagraph();
32+
introParagraph.AppendText("This report evaluates a student's performance based on their exam score. "
33+
+ "If the score meets or exceeds the passing mark, the student is considered to have passed. "
34+
+ "Otherwise, the student is marked as failed.");
35+
introParagraph.ParagraphFormat.LineSpacing = 18f;
36+
37+
// Add details of the evaluation criteria
38+
IWParagraph criteriaParagraph = document.LastSection.AddParagraph();
39+
criteriaParagraph.AppendText("Evaluation Criteria:\n"
40+
+ "• Passing Mark: 50\n"
41+
+ "• Student Score: 75\n"
42+
+ "• Condition: IF Student Score >= Passing Mark");
43+
criteriaParagraph.ParagraphFormat.LineSpacing = 18f;
44+
45+
// Add a paragraph with the IF field
46+
IWParagraph resultParagraph = document.LastSection.AddParagraph();
47+
resultParagraph.AppendText("Evaluation Result: ");
48+
resultParagraph.ParagraphFormat.LineSpacing = 18f;
49+
50+
// Add the IF field to show pass/fail result
51+
WIfField? gradeIfField = resultParagraph.AppendField("If", FieldType.FieldIf) as WIfField;
52+
gradeIfField!.FieldCode = "IF 75 >= 50 \"Pass ✅\" \"Fail ❌\"";
53+
54+
// Update fields to evaluate the IF condition
55+
document.UpdateDocumentFields();
56+
57+
// Return the document as a downloadable file
58+
return CreateFileResult(document, "SimpleIfField.docx");
59+
}
60+
61+
public IActionResult IfFieldWithRichContent()
62+
{
63+
// Load an existing Word document from the specified file path
64+
WordDocument document = new WordDocument(Path.GetFullPath(@"Data/Sample.docx"));
65+
66+
// Get the last paragraph in the document to append the IF field
67+
WParagraph paragraph = document.LastParagraph;
68+
69+
// Define the variable value to be used in the IF condition
70+
string product = "cycle";
71+
72+
// Append an IF field to the paragraph
73+
WField field = (WField)paragraph.AppendField("If", FieldType.FieldIf);
74+
75+
// Insert field code and rich content (tables and text) for true/false statements
76+
InsertIfFieldCode(paragraph, field, product);
77+
78+
// Update all fields in the document
79+
document.UpdateDocumentFields();
80+
81+
// Return the generated Word document as a downloadable file
82+
return CreateFileResult(document, "IfFieldWithRichContent.docx");
83+
}
84+
85+
/// <summary>
86+
/// Insert IF field code with complex true/false content (tables and text)
87+
/// </summary>
88+
private static void InsertIfFieldCode(WParagraph paragraph, WField field, string product)
89+
{
90+
// Get the index of the field in the paragraph
91+
int fieldIndex = paragraph.Items.IndexOf(field) + 1;
92+
93+
// Define the IF field condition
94+
field.FieldCode = $"IF \"{product}\" = \"cycle\" ";
95+
96+
// Move field separator and end marks to a temporary paragraph
97+
WParagraph lastPara = new WParagraph(paragraph.Document);
98+
MoveFieldMark(paragraph, fieldIndex + 1, lastPara);
99+
100+
// Insert true statement (when condition is true)
101+
paragraph = InsertTrueStatement(paragraph);
102+
103+
// Insert false statement (when condition is false)
104+
paragraph = InsertFalseStatement(paragraph);
105+
106+
// Move remaining field marks back from temporary paragraph to the original
107+
MoveFieldMark(lastPara, 0, paragraph);
108+
}
109+
110+
/// <summary>
111+
/// Moves remaining field items to another paragraph
112+
/// </summary>
113+
private static void MoveFieldMark(WParagraph paragraph, int fieldIndex, WParagraph lastPara)
114+
{
115+
// Move all items after the field index to the destination paragraph
116+
for (int i = fieldIndex; i < paragraph.Items.Count;)
117+
lastPara.Items.Add(paragraph.Items[i]);
118+
}
119+
120+
/// <summary>
121+
/// Insert the true part of the IF field with rich content (text + table)
122+
/// </summary>
123+
private static WParagraph InsertTrueStatement(WParagraph paragraph)
124+
{
125+
WTextBody ownerTextBody = paragraph.OwnerTextBody;
126+
127+
// Append heading text for the true statement
128+
WTextRange text = (WTextRange)paragraph.AppendText("\"Product Overview");
129+
text.CharacterFormat.Bold = true;
130+
paragraph.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center;
131+
132+
// Create a table with product details
133+
WTable table = (WTable)ownerTextBody.AddTable();
134+
135+
// Add rows and cells to the table with data
136+
WTableRow row = table!.AddRow() as WTableRow;
137+
row.AddCell().AddParagraph().AppendText("Mountain-200");
138+
row.AddCell().AddParagraph().AppendText("$2,294.99");
139+
140+
row = table.AddRow() as WTableRow;
141+
row.Cells[0].AddParagraph().AppendText("Mountain-300");
142+
row.Cells[1].AddParagraph().AppendText("$1,079.99");
143+
144+
row = table.AddRow() as WTableRow;
145+
row.Cells[0].AddParagraph().AppendText("Road-150");
146+
row.Cells[1].AddParagraph().AppendText("$3,578.27");
147+
148+
// Add a paragraph to close the true statement string
149+
WParagraph lastPara = (WParagraph)ownerTextBody.AddParagraph();
150+
lastPara.AppendText("\" ");
151+
return lastPara;
152+
}
153+
154+
/// <summary>
155+
/// Insert the false part of the IF field with rich content (text + table)
156+
/// </summary>
157+
private static WParagraph InsertFalseStatement(WParagraph paragraph)
158+
{
159+
WTextBody ownerTextBody = paragraph.OwnerTextBody;
160+
161+
// Append heading text for the false statement
162+
WTextRange text = (WTextRange)paragraph.AppendText("\"Juice Corner");
163+
text.CharacterFormat.Bold = true;
164+
paragraph.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center;
165+
166+
// Create a table with juice product details
167+
WTable table = (WTable)ownerTextBody.AddTable();
168+
169+
// Add rows and cells to the table with data
170+
WTableRow row = table.AddRow() as WTableRow;
171+
row.AddCell().AddParagraph().AppendText("Apple Juice");
172+
row.AddCell().AddParagraph().AppendText("$12.00");
173+
174+
row = table.AddRow() as WTableRow;
175+
row.Cells[0].AddParagraph().AppendText("Grape Juice");
176+
row.Cells[1].AddParagraph().AppendText("$15.00");
177+
178+
row = table.AddRow() as WTableRow;
179+
row.Cells[0].AddParagraph().AppendText("Hot Soup");
180+
row.Cells[1].AddParagraph().AppendText("$20.00");
181+
182+
row = table.AddRow() as WTableRow;
183+
row.Cells[0].AddParagraph().AppendText("Tender Coconut");
184+
row.Cells[1].AddParagraph().AppendText("$20.00");
185+
186+
row = table.AddRow() as WTableRow;
187+
row.Cells[0].AddParagraph().AppendText("Cherry");
188+
row.Cells[1].AddParagraph().AppendText("$25.00");
189+
190+
// Add a paragraph to close the false statement string
191+
WParagraph lastPara = (WParagraph)ownerTextBody.AddParagraph();
192+
lastPara.AppendText("\" ");
193+
return lastPara;
194+
}
195+
196+
private FileStreamResult CreateFileResult(WordDocument document, string fileName)
197+
{
198+
MemoryStream outputStream = new MemoryStream();
199+
document.Save(outputStream, FormatType.Docx);
200+
outputStream.Position = 0;
201+
return File(outputStream, "application/docx", fileName);
202+
}
203+
204+
public IActionResult Index()
205+
{
206+
return View();
207+
}
208+
209+
public IActionResult Privacy()
210+
{
211+
return View();
212+
}
213+
214+
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
215+
public IActionResult Error()
216+
{
217+
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
218+
}
219+
}
220+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<Project Sdk="Microsoft.NET.Sdk.Web">
2+
3+
<PropertyGroup>
4+
<TargetFramework>net8.0</TargetFramework>
5+
<Nullable>enable</Nullable>
6+
<ImplicitUsings>enable</ImplicitUsings>
7+
<RootNamespace>Create_IF_Field</RootNamespace>
8+
</PropertyGroup>
9+
10+
<ItemGroup>
11+
<PackageReference Include="Syncfusion.DocIO.Net.Core" Version="30.2.7" />
12+
</ItemGroup>
13+
14+
</Project>

Videos/IF-field/Data/Sample.docx

13.4 KB
Binary file not shown.
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
namespace Create_IF_Field.Models
2+
{
3+
public class ErrorViewModel
4+
{
5+
public string? RequestId { get; set; }
6+
7+
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
8+
}
9+
}

Videos/IF-field/Program.cs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
namespace Create_IF_Field
2+
{
3+
public class Program
4+
{
5+
public static void Main(string[] args)
6+
{
7+
var builder = WebApplication.CreateBuilder(args);
8+
9+
// Add services to the container.
10+
builder.Services.AddControllersWithViews();
11+
12+
var app = builder.Build();
13+
14+
// Configure the HTTP request pipeline.
15+
if (!app.Environment.IsDevelopment())
16+
{
17+
app.UseExceptionHandler("/Home/Error");
18+
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
19+
app.UseHsts();
20+
}
21+
22+
app.UseHttpsRedirection();
23+
app.UseStaticFiles();
24+
25+
app.UseRouting();
26+
27+
app.UseAuthorization();
28+
29+
app.MapControllerRoute(
30+
name: "default",
31+
pattern: "{controller=Home}/{action=Index}/{id?}");
32+
33+
app.Run();
34+
}
35+
}
36+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
{
2+
"$schema": "http://json.schemastore.org/launchsettings.json",
3+
"iisSettings": {
4+
"windowsAuthentication": false,
5+
"anonymousAuthentication": true,
6+
"iisExpress": {
7+
"applicationUrl": "http://localhost:12747",
8+
"sslPort": 44373
9+
}
10+
},
11+
"profiles": {
12+
"http": {
13+
"commandName": "Project",
14+
"dotnetRunMessages": true,
15+
"launchBrowser": true,
16+
"applicationUrl": "http://localhost:5055",
17+
"environmentVariables": {
18+
"ASPNETCORE_ENVIRONMENT": "Development"
19+
}
20+
},
21+
"https": {
22+
"commandName": "Project",
23+
"dotnetRunMessages": true,
24+
"launchBrowser": true,
25+
"applicationUrl": "https://localhost:7241;http://localhost:5055",
26+
"environmentVariables": {
27+
"ASPNETCORE_ENVIRONMENT": "Development"
28+
}
29+
},
30+
"IIS Express": {
31+
"commandName": "IISExpress",
32+
"launchBrowser": true,
33+
"environmentVariables": {
34+
"ASPNETCORE_ENVIRONMENT": "Development"
35+
}
36+
}
37+
}
38+
}

Videos/IF-field/README.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# How to Create an IF Field in a Word Document Using the .NET Word Library
2+
3+
This repository provides an example of how to create an **IF Field** in a Word document using the **Syncfusion .NET Word Library (DocIO)**. It demonstrates how to create a simple IF field and how to use it with paragraphs and tables.
4+
5+
## Process behind IF Field integration
6+
7+
The sample showcases how IF fields can be programmatically added to a Word document to display different content based on conditions. Users can insert simple IF fields for text-based results or add rich content such as tables and formatted text for true/false cases.
8+
9+
IF field scenarios supported in this sample:
10+
- **Simple IF Field**: Displays pass/fail status based on a numeric condition.
11+
- **IF Field with Rich Content**: Inserts tables and formatted text for true/false statements.
12+
13+
## Steps to use the sample
14+
15+
1. Open the ASP.NET Core application where the Syncfusion DocIO package is installed.
16+
2. Run the application and click the following buttons:
17+
- **Create Simple IF Field**: Creates a Word document with a basic IF field.
18+
- **Create IF Field with Rich Content**: Creates a Word document with rich content based on the IF field condition.
19+
20+
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
@{
2+
ViewData["Title"] = "Home Page";
3+
}
4+
5+
<div>
6+
<h2 style="margin-bottom: 20px">Working with Word IF Fields</h2>
7+
<div>
8+
<button style="width: 300px; margin-bottom: 20px; height: 40px; display: block"
9+
onclick="location.href='@Url.Action("SimpleIfField", "Home")'">
10+
Create Simple IF Field
11+
</button>
12+
<button style="width: 300px; margin-bottom: 20px; height: 40px; display: block"
13+
onclick="location.href='@Url.Action("IfFieldWithRichContent", "Home")'">
14+
Create IF Field with Rich Content
15+
</button>
16+
</div>
17+
</div>
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
@{
2+
ViewData["Title"] = "Privacy Policy";
3+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
@model ErrorViewModel
2+
@{
3+
ViewData["Title"] = "Error";
4+
}
5+
6+
<h1 class="text-danger">Error.</h1>
7+
<h2 class="text-danger">An error occurred while processing your request.</h2>
8+
9+
@if (Model.ShowRequestId)
10+
{
11+
<p>
12+
<strong>Request ID:</strong> <code>@Model.RequestId</code>
13+
</p>
14+
}
15+
16+
<h3>Development Mode</h3>
17+
<p>
18+
Swapping to <strong>Development</strong> environment will display more detailed information about the error that occurred.
19+
</p>
20+
<p>
21+
<strong>The Development environment shouldn't be enabled for deployed applications.</strong>
22+
It can result in displaying sensitive information from exceptions to end users.
23+
For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>
24+
and restarting the app.
25+
</p>

0 commit comments

Comments
 (0)