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)?