What are the available options to add images to document while performing Mailmerge?

We are performing mailmerge operation to generate a document using aspose words cloud api, is there any specific to dynamically add images to the document?

@skitzosiva

To dynamically add images to a document during a mail merge operation using the Aspose.Words Cloud API, you can utilize the Image merge field. This allows you to specify an image source for each record in your data source.

Here’s a step-by-step guide on how to achieve this:

  1. Prepare your document: In your template document, insert a merge field where you want the image to appear, for example, {{ImageField}}.

  2. Set up your data source: Ensure your data source includes a field that contains the image paths or base64 strings.

  3. Perform the mail merge: Use the MailMerge method to execute the merge, passing the data source.

Here’s a sample code snippet:

import aspose.words as aw

# Load the document
doc = aw.Document("template.docx")

# Create a data source
data = [
    {"ImageField": "path/to/image1.png"},
    {"ImageField": "path/to/image2.png"}
]

# Execute mail merge
doc.mail_merge.execute(data)

# Save the output document
doc.save("output.docx")

In this example, replace "path/to/image1.png" and "path/to/image2.png" with the actual paths to your images. The ImageField in the data source should correspond to the merge field in your document.

If you have any further questions or need additional examples, please feel free to ask!

@skitzosiva You can use special field name like Image:MyImage to insert am image upon executing mail merge. For example see the attached template and sample code:

Document doc = new Document(@"C:\Temp\in.docx");
doc.MailMerge.Execute(new string[] { "MyImage" }, new string[] { @"C:\Temp\test.png" });
doc.Save(@"C:\Temp\out.docx");

You can also implement ImageFieldMerging in IFieldMergingCallback to control image insertion process upon executing mail merge.

Also, you can use DocumentBuilder in FieldMerging to insert images upon executing mail merge:

Document doc = new Document(@"C:\Temp\in.docx");
doc.MailMerge.FieldMergingCallback = new MyFieldMergingCallback();
doc.MailMerge.Execute(new string[] { "test" }, new string[] { @"C:\Temp\test.png" });
doc.Save(@"C:\Temp\out.docx");
private class MyFieldMergingCallback : IFieldMergingCallback
{
    public void FieldMerging(FieldMergingArgs args)
    {
        DocumentBuilder builder = new DocumentBuilder(args.Document);
        builder.MoveToField(args.Field, true);
        builder.InsertImage((string)args.FieldValue);
        args.Field.Remove();
    }

    public void ImageFieldMerging(ImageFieldMergingArgs args)
    {
        // Do nothing
    }
}

in.docx (14.0 KB)
out.docx (70.3 KB)

How to do this using api? can you explain please? ( we are trying to generate the report using Apex(salesforce))

@skitzosiva Do you mean Aspose.Words for Cloud?

yes right now we perform mail merge using this endpoint:

https://api.aspose.cloud/v4.0/words/templatename.docx/MailMerge?withRegions=true&fileName=finalOP.docx

we send our data as a json

First of all in your template should be an image field «Image:Img» then in your template data there must be a link to that image that should be either from your storage, with relative path or publicly available(without authorization) direct link
something like this

  "Items": [
  {
    "Caption" : "This remote image",
	"Img" : {
		"Url" : "http://public-image.com/image.jpg",
		"Width" : "100px",
		"Height" : "50px"
		}
  },
  {
	"Caption" : "This is image from storage",
	"Img" : "Images/ImageFromStorage.jpg"
  }
  ]
}

Can you share a word template with this image field please?

TestMailMergeWithImages.docx (12.5 KB)

Something like this

Thank you! I’ll check and comeback

{
“Caption”: “This image is from storage”,
“Img”: {
“Img”: “Images/Killua.jpg”,
“Width”: “100px”,
“Height”: “50px”
}
}

this is the json that im trying to send and i have a folder on my aspose named Images inside i have the image killua.jpg but still my output is empty
Test_Output_1 (1).docx (9.7 KB)
image.png (168.7 KB)

image.png (139.1 KB)

Let me check myself

also i want to send multiple images

What SDK do you use? I will create a sample for you.

We don’t use any sdk , im trying to mailmerge using apex

I see, I will create a template code for mailmerge in apex

Do you have any update on this please?

I will share the code a bit later today. Thanks for your patience.

Here is the simplified version of your request other parameters you may want to use you can find at our reference page Aspose.Words Cloud - API References

public static void mailMerge(String templateFileName, String jsonData, String destFileName) {
        String token = GetJWT();
        
        Http http = new Http();
        HttpRequest req = new HttpRequest();
        
        String endpoint = 'https://api-mirror.aspose.cloud/v4.0/words/' + 
            EncodingUtil.urlEncode(templateFileName, 'UTF-8') + '/MailMerge' +
            '?destfilename=' + EncodingUtil.urlEncode(destFileName, 'UTF-8');
        
        req.setEndpoint(endpoint);
        req.setMethod('PUT');
        req.setHeader('Authorization', 'Bearer ' + token);
        req.setHeader('Content-Type', 'application/json');
        req.setBody(jsonData);
        
        HttpResponse res = http.send(req);
        
        if (res.getStatusCode() >= 200 && res.getStatusCode() < 300) {
            System.debug('Mail merge request successful: ' + res.getBody());
        } else {
            System.debug('Mail merge request failed. Status: ' + res.getStatusCode() + ' Response: ' + res.getBody());
        }
        
        System.debug('Status: ' + res.getStatus());
        System.debug('Body: ' + res.getBody());
    }

And here you can find how do I create a json for testing

String body = JSON.serialize(new Map<String, Object>{
    'Items' => new List<Object>{
        new Map<String, Object>{
            'Caption' => 'This is the first image !!!',
            'Img' => 'Images/image.png'
        },
        new Map<String, Object>{
            'Caption' => 'This is the second image !!!',
            'Img' => 'Images/image1.png'
        }
    }
});