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="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    ...
    ...

    <dependencies>
        <dependency>
            <groupId>e-iceblue</groupId>
            <artifactId>spire.doc.free</artifactId>
            <version>5.2.0</version>
        </dependency>
    </dependencies>

    <repositories>
        <repository>
            <id>com.e-iceblue</id>
            <name>e-iceblue</name>
            <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
        </repository>
    </repositories>
</project>

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.io.FileOutputStream;
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[]{
                "academicYear",
                "registrationNumber",
                "fullName",
                "gender",
                "telephone",
                "address",
                "paymentAmount",
                "inWords",
                "paymentDate",
                "receivedBy",
                "picture"
        };
        String[] fieldValues = new String[]{
                "2021/2022",
                "0001/REG/2021",
                "Foo Bar",
                "M",
                "081234567890",
                "Sudirman Street 100",
                NUMBER_FORMAT.format(1575000),
                "One Million Five Hundred Seventy Five Thousand",
                DATE_FORMAT.format(new Date()),
                "John Doe",
                "/duke.png"
        };

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

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

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

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

Mail Merge Result Document

How do I install Calibri font in Ubuntu?

I need to create a Microsoft Word Mail Merge document in my Java Spring MVC application. But running it in Ubuntu server resulting in a document that missing the default font use in the document, which is the Calibri font. So I need to install the font in Ubuntu to make the document looks as expected.

Here what I need to do to install the font in my Ubuntu box. Starts by updating the repository package list to get latest packages information for upgrades or new package installation.

sudo apt-get update

Then install FontForge in our system. FontForge is a free and open source font editor, but in this case it will help to do the font conversion in the installation script on the upcoming step.

sudo apt-get install fontforge

Install the Microsoft Cabinet file un-packer. This is required for the next script to successfully install the fonts.

sudo apt-get install cabextract

The following script will install Microsoft Vista TrueType Fonts (TTF) in Ubuntu. It includes the following fonts, Calibri, Cambria, Candara, Consolas, Constantia, and Corbel.

wget https://gist.githubusercontent.com/maxwelleite/10774746/raw/ttf-vista-fonts-installer.sh -q -O - | sudo bash

Run the next command to see if the font successfully installed. You will see the Calibri fonts in the result if the fonts successfully installed.

fc-list | grep Calibri

Here are the list of installed Calibri fonts.

/usr/share/fonts/truetype/vista/calibriz.ttf: Calibri:style=Bold Italic
/usr/share/fonts/truetype/vista/calibrii.ttf: Calibri:style=Italic
/usr/share/fonts/truetype/vista/calibrib.ttf: Calibri:style=Bold
/usr/share/fonts/truetype/vista/calibri.ttf: Calibri:style=Regular

How do I replace text in Microsoft Word document using Apache POI?

The code snippet below show you how you can replace string in Microsoft Word document using the Apache POI library. The class below have three method, the openDocument(), saveDocument() and replaceText().

The routine for replacing text is implemented in the replaceText() method. This method take the HWPFDocument, the String to find and the String to replace it as parameters. The openDocument() opens the Word document. When the text replacement is done the Word document will be saved by the saveDocument() method.

And here is the complete code snippet. It will replace every dolor texts into d0l0r texts in the source document, the lipsum.doc, and save the result in a new document called new-lipsum.doc.

package org.kodejava.poi;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.CharacterRun;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.hwpf.usermodel.Section;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;

public class WordReplaceText {
    private static final String SOURCE_FILE = "lipsum.doc";
    private static final String OUTPUT_FILE = "new-lipsum.doc";

    public static void main(String[] args) throws Exception {
        WordReplaceText instance = new WordReplaceText();
        try (HWPFDocument doc = instance.openDocument(SOURCE_FILE)) {
            if (doc != null) {
                HWPFDocument newDoc = instance.replaceText(doc, "dolor", "d0l0r");
                instance.saveDocument(newDoc, OUTPUT_FILE);
            }
        }
    }

    private HWPFDocument replaceText(HWPFDocument doc, String findText, String replaceText) {
        Range range = doc.getRange();
        for (int numSec = 0; numSec < range.numSections(); ++numSec) {
            Section sec = range.getSection(numSec);
            for (int numPara = 0; numPara < sec.numParagraphs(); numPara++) {
                Paragraph para = sec.getParagraph(numPara);
                for (int numCharRun = 0; numCharRun < para.numCharacterRuns(); numCharRun++) {
                    CharacterRun charRun = para.getCharacterRun(numCharRun);
                    String text = charRun.text();
                    if (text.contains(findText)) {
                        charRun.replaceText(findText, replaceText);
                    }
                }
            }
        }
        return doc;
    }

    private HWPFDocument openDocument(String file) throws Exception {
        URL res = getClass().getClassLoader().getResource(file);
        HWPFDocument document = null;
        if (res != null) {
            document = new HWPFDocument(new POIFSFileSystem(
                    new File(res.getPath())));
        }
        return document;
    }

    private void saveDocument(HWPFDocument doc, String file) {
        try (FileOutputStream out = new FileOutputStream(file)) {
            doc.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>5.2.3</version>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-scratchpad</artifactId>
        <version>5.2.3</version>
    </dependency>
</dependencies>

Maven Central Maven Central