Apply Custom Formatting to Fields
Sometimes users need to apply custom formatting to fields. In this article, we will look at a couple of examples of how this can be done.
To learn more options, see the full list of properties for each field type in the corresponding class in the Fields namespace.
How to Apply Custom Formatting to Field Result
Aspose.Words provides API for custom formatting of field’s result. You can implement IFieldResultFormatter interface to control how the field result is formatted. You can apply numeric format switch, i.e. # “#.##”, date/time format switch, i.e. @ “dd.MM.yyyy”, and number format switch, i.e. * Ordinal.
The following code example shows how to apply custom formatting for the field result:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
FieldResultFormatter formatter = new FieldResultFormatter("${0}", "Date: {0}", "Item # {0}:"); | |
doc.FieldOptions.ResultFormatter = formatter; | |
// Our field result formatter applies a custom format to newly created fields of three types of formats. | |
// Field result formatters apply new formatting to fields as they are updated, | |
// which happens as soon as we create them using this InsertField method overload. | |
// 1 - Numeric: | |
builder.InsertField(" = 2 + 3 \\# $###"); | |
Assert.AreEqual("$5", doc.Range.Fields[0].Result); | |
Assert.AreEqual(1, formatter.CountFormatInvocations(FieldResultFormatter.FormatInvocationType.Numeric)); | |
// 2 - Date/time: | |
builder.InsertField("DATE \\@ \"d MMMM yyyy\""); | |
Assert.IsTrue(doc.Range.Fields[1].Result.StartsWith("Date: ")); | |
Assert.AreEqual(1, formatter.CountFormatInvocations(FieldResultFormatter.FormatInvocationType.DateTime)); | |
// 3 - General: | |
builder.InsertField("QUOTE \"2\" \\* Ordinal"); | |
Assert.AreEqual("Item # 2:", doc.Range.Fields[2].Result); | |
Assert.AreEqual(1, formatter.CountFormatInvocations(FieldResultFormatter.FormatInvocationType.General)); | |
formatter.PrintFormatInvocations(); |
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git. | |
/// <summary> | |
/// When fields with formatting are updated, this formatter will override their formatting | |
/// with a custom format, while tracking every invocation. | |
/// </summary> | |
private class FieldResultFormatter : IFieldResultFormatter | |
{ | |
public FieldResultFormatter(string numberFormat, string dateFormat, string generalFormat) | |
{ | |
mNumberFormat = numberFormat; | |
mDateFormat = dateFormat; | |
mGeneralFormat = generalFormat; | |
} | |
public string FormatNumeric(double value, string format) | |
{ | |
if (string.IsNullOrEmpty(mNumberFormat)) | |
return null; | |
string newValue = String.Format(mNumberFormat, value); | |
FormatInvocations.Add(new FormatInvocation(FormatInvocationType.Numeric, value, format, newValue)); | |
return newValue; | |
} | |
public string FormatDateTime(DateTime value, string format, CalendarType calendarType) | |
{ | |
if (string.IsNullOrEmpty(mDateFormat)) | |
return null; | |
string newValue = String.Format(mDateFormat, value); | |
FormatInvocations.Add(new FormatInvocation(FormatInvocationType.DateTime, $"{value} ({calendarType})", format, newValue)); | |
return newValue; | |
} | |
public string Format(string value, GeneralFormat format) | |
{ | |
return Format((object)value, format); | |
} | |
public string Format(double value, GeneralFormat format) | |
{ | |
return Format((object)value, format); | |
} | |
private string Format(object value, GeneralFormat format) | |
{ | |
if (string.IsNullOrEmpty(mGeneralFormat)) | |
return null; | |
string newValue = String.Format(mGeneralFormat, value); | |
FormatInvocations.Add(new FormatInvocation(FormatInvocationType.General, value, format.ToString(), newValue)); | |
return newValue; | |
} | |
public int CountFormatInvocations(FormatInvocationType formatInvocationType) | |
{ | |
if (formatInvocationType == FormatInvocationType.All) | |
return FormatInvocations.Count; | |
return FormatInvocations.Count(f => f.FormatInvocationType == formatInvocationType); | |
} | |
public void PrintFormatInvocations() | |
{ | |
foreach (FormatInvocation f in FormatInvocations) | |
Console.WriteLine($"Invocation type:\t{f.FormatInvocationType}\n" + | |
$"\tOriginal value:\t\t{f.Value}\n" + | |
$"\tOriginal format:\t{f.OriginalFormat}\n" + | |
$"\tNew value:\t\t\t{f.NewValue}\n"); | |
} | |
private readonly string mNumberFormat; | |
private readonly string mDateFormat; | |
private readonly string mGeneralFormat; | |
private List<FormatInvocation> FormatInvocations { get; } = new List<FormatInvocation>(); | |
private class FormatInvocation | |
{ | |
public FormatInvocationType FormatInvocationType { get; } | |
public object Value { get; } | |
public string OriginalFormat { get; } | |
public string NewValue { get; } | |
public FormatInvocation(FormatInvocationType formatInvocationType, object value, string originalFormat, string newValue) | |
{ | |
Value = value; | |
FormatInvocationType = formatInvocationType; | |
OriginalFormat = originalFormat; | |
NewValue = newValue; | |
} | |
} | |
public enum FormatInvocationType | |
{ | |
Numeric, DateTime, General, All | |
} | |
} |
How to evaluate IF
condition
If you want to evaluate IF
condition after mail merge, you can use the EvaluateCondition method that immediately returns the result of the expression evaluation.
The following code example shows how to use this method:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git. | |
DocumentBuilder builder = new DocumentBuilder(); | |
FieldIf field = (FieldIf) builder.InsertField("IF 1 = 1", null); | |
FieldIfComparisonResult actualResult = field.EvaluateCondition(); | |
Console.WriteLine(actualResult); |
How to Apply Custom Formatting to Time Field
By default Aspose.Words updates TIME
field with current culture short time format. We figured out that there is a difference between Microsoft Word formatting and .NET/Windows formatting, and also between different .NET Framework versions. If you want to format the TIME
field according to your requirement, you can achieve this by implementing IFieldUpdateCultureProvider interface.
The following code examples shows how to apply custom formatting to the TIME
field:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.InsertField(FieldType.FieldTime, true); | |
doc.FieldOptions.FieldUpdateCultureSource = FieldUpdateCultureSource.FieldCode; | |
doc.FieldOptions.FieldUpdateCultureProvider = new FieldUpdateCultureProvider(); | |
doc.Save(ArtifactsDir + "WorkingWithFields.FieldUpdateCulture.pdf"); |
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git. | |
class FieldUpdateCultureProvider : IFieldUpdateCultureProvider | |
{ | |
public CultureInfo GetCulture(string name, Field field) | |
{ | |
switch (name) | |
{ | |
case "ru-RU": | |
CultureInfo culture = new CultureInfo(name, false); | |
DateTimeFormatInfo format = culture.DateTimeFormat; | |
format.MonthNames = new[] | |
{ | |
"месяц 1", "месяц 2", "месяц 3", "месяц 4", "месяц 5", "месяц 6", "месяц 7", "месяц 8", | |
"месяц 9", "месяц 10", "месяц 11", "месяц 12", "" | |
}; | |
format.MonthGenitiveNames = format.MonthNames; | |
format.AbbreviatedMonthNames = new[] | |
{ | |
"мес 1", "мес 2", "мес 3", "мес 4", "мес 5", "мес 6", "мес 7", "мес 8", "мес 9", "мес 10", | |
"мес 11", "мес 12", "" | |
}; | |
format.AbbreviatedMonthGenitiveNames = format.AbbreviatedMonthNames; | |
format.DayNames = new[] | |
{ | |
"день недели 7", "день недели 1", "день недели 2", "день недели 3", "день недели 4", | |
"день недели 5", "день недели 6" | |
}; | |
format.AbbreviatedDayNames = new[] | |
{ "день 7", "день 1", "день 2", "день 3", "день 4", "день 5", "день 6" }; | |
format.ShortestDayNames = new[] { "д7", "д1", "д2", "д3", "д4", "д5", "д6" }; | |
format.AMDesignator = "До полудня"; | |
format.PMDesignator = "После полудня"; | |
const string pattern = "yyyy MM (MMMM) dd (dddd) hh:mm:ss tt"; | |
format.LongDatePattern = pattern; | |
format.LongTimePattern = pattern; | |
format.ShortDatePattern = pattern; | |
format.ShortTimePattern = pattern; | |
return culture; | |
case "en-US": | |
return new CultureInfo(name, false); | |
default: | |
return null; | |
} | |
} | |
} |