Hi,
I am using Aspose .NET to generate a Mail Merge report.
Everything works fine, except when I place the “MyHtml” merge field in a table cell in the template document.
If “MyHtml” contains a HTML table, the HTML table is compressed horizontally even though I explicitly set the tables to Auto Fit to Contents.
The following is the code:
public override void GenerateReport()
{
string TemplatePath = Path.Combine(TemplateFolder, ReportTemplate.FileName);
// Open the template document.
var Doc = new Document(TemplatePath);
// Add a handler for the MergeField event.
HandleMergeFieldCustomLogic customLogicHandler = new HandleMergeFieldCustomLogic();
Doc.MailMerge.FieldMergingCallback = customLogicHandler;
Doc.NodeChangingCallback = customLogicHandler;
// Execute the nested mail merge with regions
DataSet ds = GetDataSet();
Doc.MailMerge.ExecuteWithRegions(ds);
foreach (Aspose.Words.Tables.Table table in customLogicHandler.InsertedHtmlTables)
{
table.AllowAutoFit = false;
table.AutoFit(Aspose.Words.Tables.AutoFitBehavior.AutoFitToContents);
}
}
private class HandleMergeFieldCustomLogic : IFieldMergingCallback, INodeChangingCallback
{
private DocumentBuilder mBuilder;
private bool IsHtmlTable = false;
public readonly List InsertedHtmlTables = new List();
#region IFieldMergingCallback
void IFieldMergingCallback.FieldMerging(FieldMergingArgs e)
{
if (mBuilder == null)
mBuilder = new DocumentBuilder(e.Document);
// This way we catch the beginning of a new row.
if (e.FieldName.Equals("MyHtml"))
{
string FieldValue = e.FieldValue as string;
if (!string.IsNullOrWhiteSpace(FieldValue))
{
// Move to Field
mBuilder.MoveToField(e.Field, true);
#region Insert HTML
// Set this flag to true, so that we get only Inserted Html tables after the InsertHtml call
IsHtmlTable = true;
mBuilder.InsertHtml(FieldValue);
// Set this flag to false, so that we ignore all other tables after the InsertHtml call
IsHtmlTable = false;
#endregion Insert HTML
// Remove the string representation of HTML
e.Text = string.Empty;
}
}
}
void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
{
// Do nothing.
}
#endregion IFieldMergingCallback
#region INodeChangingCallback
void INodeChangingCallback.NodeInserted(NodeChangingArgs args)
{
if (args.Node.NodeType == NodeType.Table && IsHtmlTable)
{
InsertedHtmlTables.Add(args.Node);
}
}
void INodeChangingCallback.NodeInserting(NodeChangingArgs args)
{
// Do Nothing
}
void INodeChangingCallback.NodeRemoved(NodeChangingArgs args)
{
// Do Nothing
}
void INodeChangingCallback.NodeRemoving(NodeChangingArgs args)
{
// Do Nothing
}
#endregion INodeChangingCallback
}
Regards,
Joseph Wee