How do I mail merge Word document in Java?

The following example will show you how to use the E-iceblue‘s free Spire.Doc for Java to perform mail merge operations on MS Word documents.

Create Maven Project and Add Dependencies

Create a maven project and add the following dependencies and repositories in your project’s pom.xml file.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="" xmlns:xsi=""




Create Mail Merge Template in Microsoft Word

  • Create a new Word document.
  • Place your cursor where you want to add a merge field.

MS Word Mail Merge Template

  • Click the Insert menu, Quick Parts, Fields…
  • In the Field names select MergeField and enter the field name and press OK.

Merge Field

  • To create merge field for image you need to prefix the field name with Image:
  • When finished save the document.

The Mail Merge Code Snippet

The code snippet reads the mail merge template from a file called Receipt.docx. For the image we use a duke.png. Both of these files must be placed in the /src/main/resources directory in your maven project so that the code can read it.

package org.kodejava.example.spire;

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.reporting.MergeImageFieldEventArgs;
import com.spire.doc.reporting.MergeImageFieldEventHandler;

import java.awt.Dimension;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class MailMergeExample {
    public static final Locale LOCALE = new Locale("id", "ID");
    public static final DateFormat DATE_FORMAT = new SimpleDateFormat("dd-MMMM-yyyy", LOCALE);
    public static final NumberFormat NUMBER_FORMAT = NumberFormat.getCurrencyInstance(LOCALE);

    public static void main(String[] args) {
        String[] fieldNames = new String[]{
        String[] fieldValues = new String[]{
                "Foo Bar",
                "Sudirman Street 100",
                "One Million Five Hundred Seventy Five Thousand",
                DATE_FORMAT.format(new Date()),
                "John Doe",

        try {
            Document document = new Document();
            document.loadFromStream(MailMergeExample.class.getResourceAsStream("/Receipt.docx"), FileFormat.Auto);
            document.getMailMerge().MergeImageField = new MergeImageFieldEventHandler() {
                public void invoke(Object o, MergeImageFieldEventArgs field) {
                    field.setPictureSize(new Dimension(66, 88));

                    String path = field.getImageFileName();
                    if (path != null && !path.isEmpty()) {
                        try {
                        } catch (Exception e) {
            document.getMailMerge().execute(fieldNames, fieldValues);

            String fileName = "Receipt.pdf";
            FileOutputStream fos = new FileOutputStream(fileName);
            document.saveToStream(fos, FileFormat.PDF);
        } catch (Exception e) {

Running the code will create a file called Receipt.pdf with the content as shown in the image below.

Mail Merge Result Document

How to truncate a string after n number of words?

package org.kodejava.regex;

public class GetNumberOfWordsFromString {
    public static void main(String[] args) {
        String text = "The quick brown fox jumps over the lazy dog.";

        String one = truncateAfterWords(1, text);
        System.out.println("1 = " + one);

        String two = truncateAfterWords(2, text);
        System.out.println("2 = " + two);

        String four = truncateAfterWords(4, text);
        System.out.println("4 = " + four);

        String six = truncateAfterWords(6, text);
        System.out.println("6 = " + six);

     * Truncate a string after n number of words.
     * @param words number of words to truncate after.
     * @param text  the text.
     * @return truncated text.
    public static String truncateAfterWords(int words, String text) {
        String regex = String.format("^((?:\\W*\\w+){%s}).*$", words);
        return text.replaceAll(regex, "$1");

The result of the snippet:

1 = The
2 = The quick
4 = The quick brown fox
6 = The quick brown fox jumps over

How do I reverse a string by word?

In the other examples on this website you might have seen how to reverse a string using StringBuffer, StringUtils from Apache Commons Lang library or using the CharacterIterator.

In this example you’ll see another way that you can use to reverse a string by word. Here we use the StringTokenizer and the Stack class.

package org.kodejava.util;

import java.util.Stack;
import java.util.StringTokenizer;

public class ReverseStringByWord {
    public static void main(String[] args) {
        // The string that we'll reverse
        String text = "Jackdaws love my big sphinx of quartz";

        // We use StringTokenize to get each word of the string. You might try
        // to use the String.split() method if you want.
        StringTokenizer st = new StringTokenizer(text, " ");

        // To reverse it we can use the Stack class, which implements the LIFO
        // (last-in-first-out).
        Stack<String> stack = new Stack<>();
        while (st.hasMoreTokens()) {

        // Print each word in reverse order
        while (!stack.isEmpty()) {
            System.out.print(stack.pop() + " ");