Free Support Forum - aspose.com

How to change font color or other attribute in IFieldMergingCallback

I was unsuccessful in changing color of data field during the callback for mail merge region.

How should I initialize the document builder to point at the correct field cell currently being processed in order to set font attributes?

Please review code below. I was assuming that the document builder position is already at the merged field. Thanks.

private void HandleGroupElements() {

_reportDocument.MailMerge.FieldMergingCallback = new HandleGroupElement(_reportDocument);
dataTable.TableName = element.DataElementName;
_reportDocument.MailMerge.ExecuteWithRegions(dataTable);
}

private class HandleGroupElement : IFieldMergingCallback
{
void IFieldMergingCallback.FieldMerging(FieldMergingArgs e)
{
_mBuilder.Font.Color = Color.Red;
_mBuilder.Font.Bold = true;
_mBuilder.Font.Italic = false;
_mBuilder.Font.Underline = Underline.Single;
}

void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs e)
{
}
internal HandleGroupElement(Document doc)
{
_mBuilder = new DocumentBuilder(doc);
}
private readonly DocumentBuilder _mBuilder;
}

Hi

Thanks for your request. To achieve this you should insert the value of the merge field yourself. For instance, see the following code:

[Test]

public void Test001()

{

Document doc = new Document(@"Test001\in.doc");

doc.MailMerge.FieldMergingCallback = new HandleGroupElement(doc);

doc.MailMerge.Execute(new string[] {"test"}, new object[] {"this is value of mergefield"});

doc.Save(@"Test001\out.doc");

}

private class HandleGroupElement : IFieldMergingCallback

{

void IFieldMergingCallback.FieldMerging(FieldMergingArgs e)

{

// Move DocumentBuilder cursor to the field.

_mBuilder.MoveToField(e.Field, false);

// Change font settings.

_mBuilder.Font.Color = Color.Red;

_mBuilder.Font.Bold = true;

_mBuilder.Font.Italic = false;

_mBuilder.Font.Underline = Underline.Single;

// Insert value of the mergefield using DocumentBuilder.

_mBuilder.Write(e.FieldValue.ToString());

// Set text of the field to the empty string.

e.Text = "";

}

void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs e)

{

}

internal HandleGroupElement(Document doc)

{

_mBuilder = new DocumentBuilder(doc);

}

private readonly DocumentBuilder _mBuilder;

}

Hope this helps.

Best regards,