MailMerge with html content

I know that the DocumentBuilder has an InsertHtml() method. What I need to know is how can I merge html content into a report using merge fields? Is there an accepted pattern for that?

I tried searching the forum, but I keep getting an error page.

Thanks

Hi Charles,

Thanks for your inquiry. In your case, we suggest you please implement IFieldMergingCallback interface to achieve your requirements. Following code example shows how to mail merge HTML data into a document. 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.
    }
}
1 Like

hello,
had the same problem, it fixed it but only partially.
in fact, it leaves an empty line in my merged document (where the field is actually, but actually merged with e.text = “” value )

sovled by adding the following cleanup option :

MailMergeCleanupOptions.RemoveEmptyParagraphs

@CarlVerret

It is nice to hear from you that your problem has been solved. Please feel free to ask if you have any question about Aspose.Words, we will be happy to help you.