How to insert HTML using MailMerge

Hello ,

I am using MailMerge feature for export to word.

Data may contain HTML for some Field , I want that HTML should be rendered , HTML text should not be shown.

How it should be get done…

Regards ,

Hi Ashish,

Thanks for your inquiry.
I suggest you please implement IFieldMergingCallback interface if you
want to control how data is inserted into merge fields during a mail
merge operation. In your case, I suggest you please use following code
snippet to achieve your requirements. Hope this helps you.

// File 'MailMerge.InsertHtml.doc' has merge field named 'htmlField1' in it.
// File 'MailMerge.HtmlData.html' contains some valid Html data.
// The same approach can be used when merging HTML data from database.
public void MailMergeInsertHtml()
{
    Document doc = new Document(MyDir + "MailMerge.InsertHtml.doc");
    // Add a handler for the MergeField event.
    doc.MailMerge.FieldMergingCallback = new HandleMergeFieldInsertHtml();
    // Load some Html from file.
    StreamReader sr = File.OpenText(MyDir + "MailMerge.HtmlData.html");
    string htmltext = sr.ReadToEnd();
    sr.Close();
    // Execute mail merge.
    doc.MailMerge.Execute(new string[] { "htmlField1" }, new string[] { htmltext });
    // Save resulting document with a new name.
    doc.Save(MyDir + "MailMerge.InsertHtml Out.doc");
}
private class HandleMergeFieldInsertHtml : IFieldMergingCallback
{
    /// 
    /// This is called when merge field is actually merged with data in the document.
    /// 
    void IFieldMergingCallback.FieldMerging(FieldMergingArgs e)
    {
        // All merge fields that expect HTML data should be marked with some prefix, e.g. 'html'.
        if (e.DocumentFieldName.StartsWith("html"))
        {
            // Insert the text for this merge field as HTML data, using DocumentBuilder.
            DocumentBuilder builder = new DocumentBuilder(e.Document);
            builder.MoveToMergeField(e.DocumentFieldName);
            builder.InsertHtml((string)e.FieldValue);
            // The HTML text itself should not be inserted.
            // We have already inserted it as an HTML.
            e.Text = "";
        }
    }
    void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs e)
    {
        // Do nothing.
    }
}