Articles in this section
Category / Section

How to replace merge field with HTML string using Mail merge in Java

4 mins read

Mail merge is a process of merging data from a data source to a Word template document. Syncfusion® Java Word library(Essential® DocIO) is used to generate reports like an invoice, payroll, letter, and more, by performing a mail merge faster in a batch process without Microsoft Word or interop dependencies. Using this library, you can replace the merge field with an HTML string using the Mail merge in Java.

Replace merge field with HTML string using Java:

  1. Create a new ReplaceMergeFieldWithHTML.java file and include the following namespaces.

JAVA

import java.nio.file.*;
import java.util.*;
import com.syncfusion.docio.*;
import com.syncfusion.javahelper.system.collections.generic.ListSupport;
import com.syncfusion.javahelper.system.data.*;
  1. Use the following code sample to replace the merge field in a Word document with an HTML string using Mail merge.

JAVA

// Collection to store the HTML string
static HashMap<wparagraph, hashmap<integer,="" string="">> paraToInsertHTML = new HashMap<>();


// Opens the template document.
WordDocument document = new WordDocument("Template.docx");

// Creates mail merge events handler to replace merge field with HTML.
document.getMailMerge().MergeField.add("mergeFieldEvent", new MergeFieldEventHandler() {
   ListSupport<mergefieldeventhandler> delegateList = new ListSupport<mergefieldeventhandler>(
   		MergeImageFieldEventHandler.class);
   @Override
   public void invoke(Object sender, MergeFieldEventArgs args) throws Exception{
       mergeFieldEvent(sender, args);
   }
   
   @Override
   public void add(MergeFieldEventHandler delegate) throws Exception {
   	if (delegate != null)
   		delegateList.add(delegate);
   }
   
   @Override
   public void dynamicInvoke(Object... args) throws Exception {
   	 mergeFieldEvent((Object) args[0], (MergeFieldEventArgs) args[1]);
   }
   
   @Override
   public void remove(MergeFieldEventHandler delegate) throws Exception {
   	if (delegate != null)
   		delegateList.remove(delegate);
   }
});

// Gets data to perform mail merge.
DataTableSupport table = getDataTable();
// Performs the mail merge.
document.getMailMerge().execute(table);
// Append HTML to paragraph.
insertHtml();
// Saves the Word document instance.
document.save("Sample.docx");
//Closes the Word document.
document.close();
  1. Use the following helper method to get the paragraph where to replace merge field with HTML string by using MergeFieldEventHandler.

JAVA

public static void mergeFieldEvent(Object sender, MergeFieldEventArgs args) throws Exception {
   if (args.getTableName().equals("HTML")) {
       if (args.getFieldName().equals("ProductList")) {
           // Gets the current merge field owner paragraph.
           WParagraph paragraph = args.getCurrentMergeField().getOwnerParagraph();
           // Gets the current merge field index in the current paragraph.
           int mergeFieldIndex = paragraph.getChildEntities().indexOf(args.getCurrentMergeField());
           // Maintain HTML in collection.
           HashMap<integer, string=""> fieldValues = new HashMap<>();
           fieldValues.put(mergeFieldIndex, args.getFieldValue().toString());
           // Maintain paragraph in collection.
           paraToInsertHTML.put(paragraph, fieldValues);
           // Set field value as empty.
           args.setText("");
       }
   }
}
  1. Use the following helper method to insert the Html content into a paragraph.

JAVA

private static void insertHtml() throws Exception{
   // Iterates through each item in the map.
   for (Map.Entry<wparagraph, hashmap<integer,="" string="">> entry : paraToInsertHTML.entrySet()) {
       WParagraph paragraph = entry.getKey();
       HashMap<integer, string=""> values = entry.getValue();
       // Iterates through each value in the map.
       for (Map.Entry<integer, string=""> valuePair : values.entrySet()) {
           int index = valuePair.getKey();
           String fieldValue = valuePair.getValue();
           // Inserts HTML string at the same position of mergefield in Word document.
           paragraph.getOwnerTextBody().insertXHTML(fieldValue, paragraph.getOwnerTextBody().getChildEntities().indexOf(paragraph), index);
       }
   }
   paraToInsertHTML.clear();
}
  1. Use the following helper method to get data to perform the Mail merge.

JAVA

private static DataTableSupport getDataTable() throws Exception{
   DataTableSupport dataTable = new DataTableSupport("HTML");
   dataTable.getColumns().add("CustomerName");
   dataTable.getColumns().add("Address");
   dataTable.getColumns().add("Phone");
   dataTable.getColumns().add("ProductList");
   DataRowSupport datarow = dataTable.newRow();
   dataTable.getRows().add(datarow);
   datarow.set("CustomerName", "Nancy Davolio");
   datarow.set("Address", "59 rue de I'Abbaye, Reims 51100, France");
   datarow.set("Phone", "1-888-936-8638");
   
   // Reads HTML string from the file.
   String htmlString =new String( Files.readAllBytes(Paths.get("File.html"))); 
   // Read the HTML file and assign it to htmlString
   
   datarow.set("ProductList", htmlString);
   return dataTable;
}

By executing the application, you will get the output Word document as follows.

image.png

You can refer to this link to know about how to run the Syncfusion® Java Word library (Essential® DocIO).

Take a moment to peruse the documentation. You can find basic Word document processing options along with the features like mail merge, merge, and split documents.

Explore more about a rich set of Syncfusion® Word Framework features.

A Github example to perform a mail merge in Word document in Java.</integer,></integer,></wparagraph,></integer,></wparagraph,>

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