|
| 1 | +using Syncfusion.DocIO; |
| 2 | +using Syncfusion.DocIO.DLS; |
| 3 | + |
| 4 | +namespace Insert_Signature_in_Word_Document_through_MailMerge |
| 5 | +{ |
| 6 | + class Program |
| 7 | + { |
| 8 | + |
| 9 | + static void Main(string[] args) |
| 10 | + { |
| 11 | + // Load the word document |
| 12 | + using (FileStream fileStream = new FileStream(Path.GetFullPath("../../../Data/Template.docx"), FileMode.Open, FileAccess.Read)) |
| 13 | + { |
| 14 | + using (WordDocument document = new WordDocument(fileStream, FormatType.Docx)) |
| 15 | + { |
| 16 | + string[] fieldNames = { "Signature" }; |
| 17 | + string[] fieldValues = { "signature.png" }; |
| 18 | + |
| 19 | + document.MailMerge.MergeImageField += MailMerge_MergeSignature; |
| 20 | + //Execute mail merge in the Word document |
| 21 | + document.MailMerge.Execute(fieldNames, fieldValues); |
| 22 | + using (FileStream outputStream = new FileStream(Path.GetFullPath("../../../Output/Result.docx"), FileMode.Create, FileAccess.Write)) |
| 23 | + { |
| 24 | + //Saves the stream as Word file |
| 25 | + document.Save(outputStream, FormatType.Docx); |
| 26 | + } |
| 27 | + } |
| 28 | + } |
| 29 | + } |
| 30 | + /// <summary> |
| 31 | + /// Binds the image from file system and fit within text box during Mail merge process by using MergeImageFieldEventHandler. |
| 32 | + /// </summary> |
| 33 | + /// <param name="sender"></param> |
| 34 | + /// <param name="args"></param> |
| 35 | + private static void MailMerge_MergeSignature(object sender, MergeImageFieldEventArgs args) |
| 36 | + { |
| 37 | + if (args.FieldName == "Signature") |
| 38 | + { |
| 39 | + string productFileName = args.FieldValue.ToString(); |
| 40 | + byte[] imageBytes = File.ReadAllBytes(@"Data/" + productFileName); |
| 41 | + MemoryStream imageStream = new MemoryStream(imageBytes); |
| 42 | + args.ImageStream = imageStream; |
| 43 | + // Get the picture to be merged |
| 44 | + WPicture picture = args.Picture; |
| 45 | + |
| 46 | + WTextBox textbox = args.CurrentMergeField.OwnerParagraph.OwnerTextBody.Owner as WTextBox; |
| 47 | + // check whether the picture is inside the text box |
| 48 | + if (textbox != null) |
| 49 | + { |
| 50 | + // Get the text box format |
| 51 | + WTextBoxFormat textBoxFormat = textbox.TextBoxFormat; |
| 52 | + |
| 53 | + if (textBoxFormat != null) |
| 54 | + { |
| 55 | + // Resize width |
| 56 | + if (picture.Width != textBoxFormat.Width) |
| 57 | + { |
| 58 | + float widthScale = textBoxFormat.Width / picture.Width * 100; |
| 59 | + picture.WidthScale = widthScale; |
| 60 | + } |
| 61 | + |
| 62 | + // Resize height |
| 63 | + if (picture.Height != textBoxFormat.Height) |
| 64 | + { |
| 65 | + float heightScale = textBoxFormat.Height / picture.Height * 100; |
| 66 | + picture.HeightScale = heightScale; |
| 67 | + } |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | + } |
| 72 | + } |
| 73 | +} |
0 commit comments