We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

Insert Html into merge field

I have user generated html that I need to insert into a word document merge field while maintaining the formatting from the HTML code. I am using Aspose.Words version 14.7.0.

TIA,

-L

P.S. I am sorry if this question has been already been answered on the forum. The search is timing out for me.

Hi Logan,


Thanks for your inquiry. Sure, you can insert Html during mail merge by using the following code snippet: I hope, this helps.

// File ‘MailMerge.InsertHtml.doc’ has merge field named ‘htmlField1’ in it.

// File ‘MailMerge.HtmlData.html’ contains some valid Html data.<o:p></o:p>

// The same approach can be used when merging HTML data from database.<o:p></o:p>

public void MailMergeInsertHtml()<o:p></o:p>

{<o:p></o:p>

Document doc = new Document(MyDir + “MailMerge.InsertHtml.doc”);<o:p></o:p>

// Add a handler for the MergeField event.<o:p></o:p>

doc.MailMerge.FieldMergingCallback = new HandleMergeFieldInsertHtml();<o:p></o:p>

// Load some Html from file.<o:p></o:p>

StreamReader sr = File.OpenText(MyDir + “MailMerge.HtmlData.html”);<o:p></o:p>

string htmltext = sr.ReadToEnd();<o:p></o:p>

sr.Close();<o:p></o:p>

// Execute mail merge.<o:p></o:p>

doc.MailMerge.Execute(new string[] { “htmlField1” }, new string[] { htmltext });<o:p></o:p>

// Save resulting document with a new name.<o:p></o:p>

doc.Save(MyDir + “MailMerge.InsertHtml Out.doc”);<o:p></o:p>

}<o:p></o:p>

private class HandleMergeFieldInsertHtml : IFieldMergingCallback<o:p></o:p>

{<o:p></o:p>

///

<o:p></o:p>

/// This is called when merge field is actually merged with data in the document.<o:p></o:p>

/// <o:p></o:p>

void IFieldMergingCallback.FieldMerging(FieldMergingArgs e)<o:p></o:p>

{<o:p></o:p>

// All merge fields that expect HTML data should be marked with some prefix, e.g. ‘html’.<o:p></o:p>

if (e.DocumentFieldName.StartsWith(“html”))<o:p></o:p>

{<o:p></o:p>

// Insert the text for this merge field as HTML data, using DocumentBuilder.<o:p></o:p>

DocumentBuilder builder = new DocumentBuilder(e.Document);<o:p></o:p>

builder.MoveToMergeField(e.DocumentFieldName);<o:p></o:p>

builder.InsertHtml((string)e.FieldValue);<o:p></o:p>

// The HTML text itself should not be inserted.<o:p></o:p>

// We have already inserted it as an HTML.<o:p></o:p>

e.Text = “”;<o:p></o:p>

}<o:p></o:p>

}<o:p></o:p>

void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs e)<o:p></o:p>

{<o:p></o:p>

// Do nothing.<o:p></o:p>

}<o:p></o:p>

}

Moreover, I would also suggest you please read the following article that outlines how to apply custom Formatting during Mail Merge:
http://www.aspose.com/docs/display/wordsnet/How+to++Apply+Custom+Formatting+during+Mail+Merge

Best regards,