//Opens the Word template document
using (WordDocument document = new WordDocument(assembly.GetManifestResourceStream(resourceName), FormatType.Docx))
{
Dictionary<WParagraph, int> pictureFieldsData = new Dictionary<WParagraph, int>();
var list = new List<WordImageParagraph>();
document.MailMerge.MergeImageField += new MergeImageFieldEventHandler(
delegate (object sender, MergeImageFieldEventArgs args)
{
//Get the image from disk during Merge.
if (args.FieldName == "ClientSignature" || args.FieldName == "UserSignature")
{
if (args.FieldName == "ClientSignature" && this.Item?.Client.Signature == null)
{
args.ImageStream = new MemoryStream();
return;
}
if (args.FieldName == "UserSignature" && App.UserInfo?.Signature == null)
{
args.ImageStream = new MemoryStream();
return;
}
args.ImageStream = args.FieldName == "ClientSignature" ?
new MemoryStream(this.Item?.Client.Signature) :
new MemoryStream(App.UserInfo.Signature);
WParagraph paragraph = args.CurrentMergeField.OwnerParagraph;
if (paragraph != null)
{
//had to change this code as we were getting duplicate OwnerParagraphs added to the dictionary
//pictureFieldsData.Add(paragraph, paragraph.Items.IndexOf(args.CurrentMergeField));
list.Add(new WordImageParagraph { Paragraph = paragraph, Index = paragraph.Items.IndexOf(args.CurrentMergeField) });
}
}
});
document.MailMerge.ExecuteGroup(this.GetMailMergeDataTable());
foreach (var item in list)
{
WParagraph paragraph = item.Paragraph as WParagraph;
//Fields are updated with pictures.
//Gets picture from the index of image field.
WPicture picture = paragraph.Items[item.Index] as WPicture;
if (picture != null)
{
//Changes the size of picture.
picture.Height = 40;
picture.Width = 65;
}
}
MemoryStream stream = new MemoryStream();
//Saves the Word file to MemoryStream
document.Save(stream, FormatType.Docx);
return stream;
}