Skip to content
Merged
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
220 changes: 220 additions & 0 deletions Videos/IF-field/Controllers/HomeController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,220 @@
using System.Diagnostics;
using Create_IF_Field.Models;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;

namespace Create_IF_Field.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;

public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}

public IActionResult SimpleIfField()
{
// Create a new Word document
WordDocument document = new WordDocument();

// Add a section and a title
document.EnsureMinimal();
IWParagraph titleParagraph = document.LastSection.AddParagraph();
titleParagraph.AppendText("Student Grade Evaluation Report");
titleParagraph.ApplyStyle(BuiltinStyle.Heading1);
titleParagraph.ParagraphFormat.LineSpacing = 18f;

// Add introductory explanation
IWParagraph introParagraph = document.LastSection.AddParagraph();
introParagraph.AppendText("This report evaluates a student's performance based on their exam score. "
+ "If the score meets or exceeds the passing mark, the student is considered to have passed. "
+ "Otherwise, the student is marked as failed.");
introParagraph.ParagraphFormat.LineSpacing = 18f;

// Add details of the evaluation criteria
IWParagraph criteriaParagraph = document.LastSection.AddParagraph();
criteriaParagraph.AppendText("Evaluation Criteria:\n"
+ "• Passing Mark: 50\n"
+ "• Student Score: 75\n"
+ "• Condition: IF Student Score >= Passing Mark");
criteriaParagraph.ParagraphFormat.LineSpacing = 18f;

// Add a paragraph with the IF field
IWParagraph resultParagraph = document.LastSection.AddParagraph();
resultParagraph.AppendText("Evaluation Result: ");
resultParagraph.ParagraphFormat.LineSpacing = 18f;

// Add the IF field to show pass/fail result
WIfField? gradeIfField = resultParagraph.AppendField("If", FieldType.FieldIf) as WIfField;
gradeIfField!.FieldCode = "IF 75 >= 50 \"Pass ✅\" \"Fail ❌\"";

// Update fields to evaluate the IF condition
document.UpdateDocumentFields();

// Return the document as a downloadable file
return CreateFileResult(document, "SimpleIfField.docx");
}

public IActionResult IfFieldWithRichContent()
{
// Load an existing Word document from the specified file path
WordDocument document = new WordDocument(Path.GetFullPath(@"Data/Sample.docx"));

// Get the last paragraph in the document to append the IF field
WParagraph paragraph = document.LastParagraph;

// Define the variable value to be used in the IF condition
string product = "cycle";

// Append an IF field to the paragraph
WField field = (WField)paragraph.AppendField("If", FieldType.FieldIf);

// Insert field code and rich content (tables and text) for true/false statements
InsertIfFieldCode(paragraph, field, product);

// Update all fields in the document
document.UpdateDocumentFields();

// Return the generated Word document as a downloadable file
return CreateFileResult(document, "IfFieldWithRichContent.docx");
}

/// <summary>
/// Insert IF field code with complex true/false content (tables and text)
/// </summary>
private static void InsertIfFieldCode(WParagraph paragraph, WField field, string product)
{
// Get the index of the field in the paragraph
int fieldIndex = paragraph.Items.IndexOf(field) + 1;

// Define the IF field condition
field.FieldCode = $"IF \"{product}\" = \"cycle\" ";

// Move field separator and end marks to a temporary paragraph
WParagraph lastPara = new WParagraph(paragraph.Document);
MoveFieldMark(paragraph, fieldIndex + 1, lastPara);

// Insert true statement (when condition is true)
paragraph = InsertTrueStatement(paragraph);

// Insert false statement (when condition is false)
paragraph = InsertFalseStatement(paragraph);

// Move remaining field marks back from temporary paragraph to the original
MoveFieldMark(lastPara, 0, paragraph);
}

/// <summary>
/// Moves remaining field items to another paragraph
/// </summary>
private static void MoveFieldMark(WParagraph paragraph, int fieldIndex, WParagraph lastPara)
{
// Move all items after the field index to the destination paragraph
for (int i = fieldIndex; i < paragraph.Items.Count;)
lastPara.Items.Add(paragraph.Items[i]);
}

/// <summary>
/// Insert the true part of the IF field with rich content (text + table)
/// </summary>
private static WParagraph InsertTrueStatement(WParagraph paragraph)
{
WTextBody ownerTextBody = paragraph.OwnerTextBody;

// Append heading text for the true statement
WTextRange text = (WTextRange)paragraph.AppendText("\"Product Overview");
text.CharacterFormat.Bold = true;
paragraph.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center;

// Create a table with product details
WTable table = (WTable)ownerTextBody.AddTable();

// Add rows and cells to the table with data
WTableRow row = table!.AddRow() as WTableRow;
row.AddCell().AddParagraph().AppendText("Mountain-200");
row.AddCell().AddParagraph().AppendText("$2,294.99");

row = table.AddRow() as WTableRow;
row.Cells[0].AddParagraph().AppendText("Mountain-300");
row.Cells[1].AddParagraph().AppendText("$1,079.99");

row = table.AddRow() as WTableRow;
row.Cells[0].AddParagraph().AppendText("Road-150");
row.Cells[1].AddParagraph().AppendText("$3,578.27");

// Add a paragraph to close the true statement string
WParagraph lastPara = (WParagraph)ownerTextBody.AddParagraph();
lastPara.AppendText("\" ");
return lastPara;
}

/// <summary>
/// Insert the false part of the IF field with rich content (text + table)
/// </summary>
private static WParagraph InsertFalseStatement(WParagraph paragraph)
{
WTextBody ownerTextBody = paragraph.OwnerTextBody;

// Append heading text for the false statement
WTextRange text = (WTextRange)paragraph.AppendText("\"Juice Corner");
text.CharacterFormat.Bold = true;
paragraph.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center;

// Create a table with juice product details
WTable table = (WTable)ownerTextBody.AddTable();

// Add rows and cells to the table with data
WTableRow row = table.AddRow() as WTableRow;
row.AddCell().AddParagraph().AppendText("Apple Juice");
row.AddCell().AddParagraph().AppendText("$12.00");

row = table.AddRow() as WTableRow;
row.Cells[0].AddParagraph().AppendText("Grape Juice");
row.Cells[1].AddParagraph().AppendText("$15.00");

row = table.AddRow() as WTableRow;
row.Cells[0].AddParagraph().AppendText("Hot Soup");
row.Cells[1].AddParagraph().AppendText("$20.00");

row = table.AddRow() as WTableRow;
row.Cells[0].AddParagraph().AppendText("Tender Coconut");
row.Cells[1].AddParagraph().AppendText("$20.00");

row = table.AddRow() as WTableRow;
row.Cells[0].AddParagraph().AppendText("Cherry");
row.Cells[1].AddParagraph().AppendText("$25.00");

// Add a paragraph to close the false statement string
WParagraph lastPara = (WParagraph)ownerTextBody.AddParagraph();
lastPara.AppendText("\" ");
return lastPara;
}

private FileStreamResult CreateFileResult(WordDocument document, string fileName)
{
MemoryStream outputStream = new MemoryStream();
document.Save(outputStream, FormatType.Docx);
outputStream.Position = 0;
return File(outputStream, "application/docx", fileName);
}

public IActionResult Index()
{
return View();
}

public IActionResult Privacy()
{
return View();
}

[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
14 changes: 14 additions & 0 deletions Videos/IF-field/Create IF Field.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>Create_IF_Field</RootNamespace>
</PropertyGroup>

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

</Project>
Binary file added Videos/IF-field/Data/Sample.docx
Binary file not shown.
9 changes: 9 additions & 0 deletions Videos/IF-field/Models/ErrorViewModel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace Create_IF_Field.Models
{
public class ErrorViewModel
{
public string? RequestId { get; set; }

public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
}
36 changes: 36 additions & 0 deletions Videos/IF-field/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
namespace Create_IF_Field
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();
}
}
}
38 changes: 38 additions & 0 deletions Videos/IF-field/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:12747",
"sslPort": 44373
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5055",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7241;http://localhost:5055",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
20 changes: 20 additions & 0 deletions Videos/IF-field/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# How to Create an IF Field in a Word Document Using the .NET Word Library

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.

## Process behind IF Field integration

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.

IF field scenarios supported in this sample:
- **Simple IF Field**: Displays pass/fail status based on a numeric condition.
- **IF Field with Rich Content**: Inserts tables and formatted text for true/false statements.

## Steps to use the sample

1. Open the ASP.NET Core application where the Syncfusion DocIO package is installed.
2. Run the application and click the following buttons:
- **Create Simple IF Field**: Creates a Word document with a basic IF field.
- **Create IF Field with Rich Content**: Creates a Word document with rich content based on the IF field condition.


17 changes: 17 additions & 0 deletions Videos/IF-field/Views/Home/Index.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
@{
ViewData["Title"] = "Home Page";
}

<div>
<h2 style="margin-bottom: 20px">Working with Word IF Fields</h2>
<div>
<button style="width: 300px; margin-bottom: 20px; height: 40px; display: block"
onclick="location.href='@Url.Action("SimpleIfField", "Home")'">
Create Simple IF Field
</button>
<button style="width: 300px; margin-bottom: 20px; height: 40px; display: block"
onclick="location.href='@Url.Action("IfFieldWithRichContent", "Home")'">
Create IF Field with Rich Content
</button>
</div>
</div>
3 changes: 3 additions & 0 deletions Videos/IF-field/Views/Home/Privacy.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
@{
ViewData["Title"] = "Privacy Policy";
}
25 changes: 25 additions & 0 deletions Videos/IF-field/Views/Shared/Error.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
@model ErrorViewModel
@{
ViewData["Title"] = "Error";
}

<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>

@if (Model.ShowRequestId)
{
<p>
<strong>Request ID:</strong> <code>@Model.RequestId</code>
</p>
}

<h3>Development Mode</h3>
<p>
Swapping to <strong>Development</strong> environment will display more detailed information about the error that occurred.
</p>
<p>
<strong>The Development environment shouldn't be enabled for deployed applications.</strong>
It can result in displaying sensitive information from exceptions to end users.
For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>
and restarting the app.
</p>
Loading
Loading