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

Free Support Forum - aspose.com

MailMerge with HTML and embedded images

Hello
Can someone help me to insert html with images? I have the following C# code. The image will not be inserted:

class Program
{
	static void Main()
	{
		var template = File.ReadAllBytes("Template.docx");
		using var ms = new MemoryStream(template);
		var document = new Document(ms);
		document.MailMerge.FieldMergingCallback = new HandleMergeFieldInsertHtml();
		var html = "test <b>bold</b> <img src=\"data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==\" />end.";
		document.MailMerge.Execute(new []{ "html_1"}, new []{ html });
		document.Save("output.pdf", SaveFormat.Pdf);
	}
}
/// <summary>
/// If the mail merge encounters a MERGEFIELD whose name starts with the "html_" prefix,
/// this callback parses its merge data as HTML content and adds the result to the document location of the MERGEFIELD.
/// </summary>
internal class HandleMergeFieldInsertHtml : IFieldMergingCallback
{
	/// <summary>
	/// Called when a mail merge merges data into a MERGEFIELD.
	/// </summary>
	void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
	{
		if (args.DocumentFieldName.StartsWith("html_", StringComparison.InvariantCulture) && args.Field.GetFieldCode().Contains("\\b"))
		{
			// Add parsed HTML data to the document's body.
			var builder = new DocumentBuilder(args.Document);
			builder.MoveToMergeField(args.DocumentFieldName);
			builder.InsertHtml((string)args.FieldValue);

			// Since we have already inserted the merged content manually,
			// we will not need to respond to this event by returning content via the "Text" property. 
			args.Text = string.Empty;
		}
	}

	void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
	{
		// Do nothing.
	}
}

I’m in a .Net Core project. Is it possible that it works with .Net 4.8, but not with .Net Core (5.0)?

@marco.wittwer

Aspose.Words does support .NET 4.8 and .NET Core 5.0. You can use the same code with both .NET versions. We have tested the scenario using .NET 4.8 and .NET Core 5.0 and have not found any issue.

In case you are using old version of Aspose.Words, we suggest you please use the latest version of Aspose.Words for .NET 21.7.

I referenced the dll only, then it did not work. When I reference the assemblies via Nuget-Package it will work.

@marco.wittwer

Perhaps, you are not using the correct DLL. Please check the attached image for Aspose.Words’ DLL. You need to use the DLL according to .NET Framework or .NET Standard.
Aspose.Words.png (3.6 KB)

It is nice to hear from you that your problem has been solved. The NuGet package installs the Aspose.Words’ DLL according to target .NET version.