Articles in this section
Category / Section

How to fit image within a text box in the Word document

5 mins read

Mail merge is a process of merging data from a data source to a Word template document. Syncfusion Essential DocIO is a .NET Word Library used to generate reports like invoice, payroll, letter, etc., by performing mail merge faster in a batch process without Microsoft Word or interop dependencies. Using this library, you can fit image within a text box in the Word document using Mail merge in C# and VB.NET.   

Fit the image within the text box using C#:

  1. Create a new C# console application project.Create Console application in Visual Studio
  2. Install Syncfusion.DocIO.WinForms NuGet package as a reference to your .NET Framework applications from the NuGet.org.Add DocIO NuGet package reference to the project
  3. Include the following namespace in the Program.cs file.

C#

using Syncfusion.DocIO.DLS;
using System.Drawing;
using System.IO;

VB

Imports Syncfusion.DocIO.DLS
Imports System.Drawing
Imports System.IO
  1. Use the following code example to fit image within a text box in the Word document using Mail merge.

C#

//Opens the template document
using (WordDocument document = new WordDocument("../../Template.docx", FormatType.Docx))
{
    //Uses the mail merge events handler for image fields
    document.MailMerge.MergeImageField += new MergeImageFieldEventHandler(MergeField_ProductImage);
    //Specifies the field names and field values
    string[] fieldNames = new string[] { "Photo" };
    string[] fieldValues = new string[] { "Logo.jpg" };
    //Executes the mail merge
    document.MailMerge.Execute(fieldNames, fieldValues);
    //Unhooks mail merge events handler
    document.MailMerge.MergeImageField -= new MergeImageFieldEventHandler(MergeField_ProductImage);
    //Saves the WordDocument instance
    document.Save("../../Sample.docx", FormatType.Docx);
}

VB

'Opens the template document
Using document As WordDocument = New WordDocument("../../Template.docx", FormatType.Docx)
    'Uses the mail merge events handler for image fields
    AddHandler document.MailMerge.MergeImageField, AddressOf MergeField_ProductImage
    'Specifies the field names and field values
    Dim fieldNames As String() = New String() {"Photo"}
    Dim fieldValues As String() = New String() {"Logo.jpg"}
    'Executes the mail merge
    document.MailMerge.Execute(fieldNames, fieldValues)
    'Unhooks mail merge events handler
    RemoveHandler document.MailMerge.MergeImageField, AddressOf MergeField_ProductImage
    'Saves the WordDocument instance
    document.Save("../../Sample.docx", FormatType.Docx)
End Using
  1. Use the following helper method to bind the image from file system and fit it within the text box during Mail merge process by using MergeImageFieldEventHandler.

C#

public void MergeField_ProductImage(object sender, MergeImageFieldEventArgs args)
{
    //Binds image from file system during mail merge
    if (args.FieldName == "Photo")
    {
        string ProductFileName = args.FieldValue.ToString();
        //Gets the image from file system
        args.Image = Image.FromFile("../../" + ProductFileName);
        //Gets the picture, to be merged for image merge field
        WPicture picture = args.Picture;
        //Gets the text box format
        WTextBoxFormat textBoxFormat = (args.CurrentMergeField.OwnerParagraph.OwnerTextBody.Owner as WTextBox).TextBoxFormat;
        //Resizes the picture to fit within text box
        float scalePercentage = 100;
        if (picture.Width != textBoxFormat.Width)
        {
            //Calculates value for width scale factor
            scalePercentage = textBoxFormat.Width / picture.Width * 100;
            //This will resize the width
            picture.WidthScale *= scalePercentage / 100;
        }
        scalePercentage = 100;
        if (picture.Height != textBoxFormat.Height)
        {
            //Calculates value for height scale factor
            scalePercentage = textBoxFormat.Height / picture.Height * 100;
            //This will resize the height
            picture.HeightScale *= scalePercentage / 100;
        }
    }
}

VB

Public Sub MergeField_ProductImage(ByVal sender As Object, ByVal args As MergeImageFieldEventArgs)
    'Binds image from file system during mail merge
    If args.FieldName = "Photo" Then
        Dim ProductFileName As String = args.FieldValue.ToString()
        'Gets the image from file system
        args.Image = Image.FromFile("../../" + ProductFileName)
        'Gets the picture, to be merged for image merge field
        Dim picture As WPicture = args.Picture
        'Gets the text box format
        Dim textBoxFormat As WTextBoxFormat = TryCast(args.CurrentMergeField.OwnerParagraph.OwnerTextBody.Owner, WTextBox).TextBoxFormat
        'Resizes the picture to fit within text box
        Dim scalePercentage As Single = 100
        If picture.Width <> textBoxFormat.Width Then
            'Calculates value for width scale factor
            scalePercentage = textBoxFormat.Width / picture.Width * 100
            'This will resize the width
            picture.WidthScale *= scalePercentage / 100
        End If
        scalePercentage = 100
        If picture.Height <> textBoxFormat.Height Then
            'Calculates value for height scale factor
            scalePercentage = textBoxFormat.Height / picture.Height * 100
            'This will resize the height
            picture.HeightScale *= scalePercentage / 100
        End If
    End If
End Sub

A complete working example to fit image within a text box in the Word document using Mail merge in C# can be downloaded from GitHub.

By executing the application, you will get the output Word document as follows. Output document after fit image within a text box in the Word document

Take a moment to peruse the documentation, where you can find basic Word document processing options along with features like mail merge, merge and split documents, find and replace text in the Word document, protect the Word documents, and most importantly PDF and Image conversions with code examples.

Explore more about the rich set of Syncfusion Word Framework features.

Note:

Starting with v16.2.0.x, if you reference Syncfusion assemblies from trial setup or from the NuGet feed, include a license key in your projects. Refer to link to learn about generating and registering Syncfusion license key in your application to use the components without trail message.

 

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please sign in to leave a comment
Access denied
Access denied