Scenario:
We have a merge field defined as: { MERGEFIELD phone # “(000) 000’-'0000” }
In the data source, the value for phone is: (734) 123-4567
Actual behavior (Aspose.Words):
Aspose interprets the value as a mathematical expression and evaluates it, returning:
-(000) 000-5178
Issue:
Aspose.Words appears to treat the value as numeric and performs subtraction due to the dash in the phone number, even though the format switch is meant to render it as a string. This behavior is causing phone numbers to not output correctly on the post-mailmerge document.
Is there any way to get around this automatic calculation?
@Robert343 I think you should simply remove the number format switches in your merge field. In this case the value will be inserted as is into the template.
This is not a solution. We need the formatting. Is there any aspose solution to this?
@Robert343 To make the formatting work it is required to pass the value as a number. You can use IFieldMergingCallback to remove parenthesis and minus characters from the value to make it possible to parse as a number. For example see the following code:
Document doc = new Document(@"C:\Temp\in.docx");
doc.MailMerge.FieldMergingCallback = new MyFieldMergingCallback();
doc.MailMerge.Execute(new string[] { "phone" }, new object[] { "(734) 123-4567" });
doc.Save(@"C:\Temp\out.docx");
private class MyFieldMergingCallback : IFieldMergingCallback
{
public void FieldMerging(FieldMergingArgs args)
{
if (args.FieldName == "phone")
args.FieldValue = ((string)args.FieldValue).Replace("(", "").Replace(")", "").Replace("-", "").Replace(" ", "");
}
public void ImageFieldMerging(ImageFieldMergingArgs args)
{
// Do nothing
}
}
in.docx (14.0 KB)
out.docx (11.1 KB)
Thank you. That is more along the lines of what I am looking for. I expanded on this a bit with this code. Do you see any issues with this code below? I’m trying to accomplish this for any of the numeric switches.
string fieldCode = args.Field.GetFieldCode();
if (fieldCode.Contains(@" \# ") == true)
{
string input = args.FieldValue.ToString();
string result = string.Empty;
bool allowDecimalCheck = (input.Count(c => c == '.') == 1);
bool allowNegativeCheck = (input.Count(c => c == '-') == 1 && input.Trim().StartsWith("-") == true);
for (int i = 0; i < input.Length; i++)
{
char currentChar = input[i];
if (char.IsDigit(currentChar))
{
result += currentChar;
}
else if (currentChar == '-' && allowNegativeCheck == true)
{
result += currentChar;
}
else if (currentChar == '.' && allowDecimalCheck == true)
{
result += currentChar;
}
}
args.FieldValue = result;
}
@Robert343 The code looks good to me.