Generating Word Documents from Templates in Java: A Developer's Guide

In modern software development, generating dynamic Word documents from templates is a common requirement for applications that produce reports, contracts, invoices, or other business documents. Java developers seeking efficient solutions for document automation can leverage Spire.Doc for Java, a robust library for processing Word files without requiring Microsoft Office.

This guide explores how to use Spire.Doc for Java to create Word documents from templates. We will cover two key approaches: replacing text placeholders and modifying bookmark content.

Java Library for Creating Word Documents

Spire.Doc for Java is a powerful library that enables developers to create, manipulate, and convert Word documents. It provides an intuitive API that allows for various operations, including the modification of text, images, and bookmarks in existing documents.

To get started, download the library from our official website and import it into your Java project. If you're using Maven, include the following dependency in your pom.xml file:

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>13.5.3</version>
    </dependency>
</dependencies>
    

Generate a Word Document by Replacing Text Placeholders

This method uses a template document containing marked placeholders (e.g., #name#, #date#) that are dynamically replaced with real data. Spire.Doc's Document.replace() method handles text substitutions efficiently, while additional APIs enable advanced replacements like inserting images at specified locations.

Steps to generate Word documents from templates by replacing text placeholders:

  • Initialize Document: A new Document object is created to work with the Word file.
  • Load the template: The template document with placeholders is loaded.
  • Create replacement mappings: A HashMap is created to store placeholder-replacement pairs.
  • Perform text replacement: The replace() method finds and replaces all instances of each placeholder.
  • Handle image insertion: The custom replaceTextWithImage() method replaces a text placeholder with an image.
  • Save the result: The modified document is saved to a specified path.
  • Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.documents.TextSelection;
import com.spire.doc.fields.DocPicture;
import com.spire.doc.fields.TextRange;

import java.util.HashMap;
import java.util.Map;

public class ReplaceTextPlaceholders {

    public static void main(String[] args) {

        // Initialize a new Document object
        Document document = new Document();

        // Load the template Word file
        document.loadFromFile("C:\\Users\\Administrator\\Desktop\\template.docx");

        // Map to hold text placeholders and their replacements
        Map replaceDict = new HashMap<>();
        replaceDict.put("#name#", "John Doe");
        replaceDict.put("#gender#", "Male");
        replaceDict.put("#birthdate#", "January 15, 1990");
        replaceDict.put("#address#", "123 Main Street");
        replaceDict.put("#city#", "Springfield");
        replaceDict.put("#state#", "Illinois");
        replaceDict.put("#postal#", "62701");
        replaceDict.put("#country#", "United States");

        // Replace placeholders in the document with corresponding values
        for (Map.Entry entry : replaceDict.entrySet()) {
            document.replace(entry.getKey(), entry.getValue(), true, true);
        }

        // Path to the image file
        String imagePath = "C:\\Users\\Administrator\\Desktop\\portrait.png";

        // Replace the placeholder “#photo#” with an image
        replaceTextWithImage(document, "#photo#", imagePath);

        // Save the modified document
        document.saveToFile("output/ReplacePlaceholders.docx", FileFormat.Docx);

        // Release resources
        document.dispose();
    }

    // Method to replace a placeholder in the document with an image
    static void replaceTextWithImage(Document document, String stringToReplace, String imagePath) {

        // Load the image from the specified path
        DocPicture pic = new DocPicture(document);
        pic.loadImage(imagePath);

        // Find the placeholder in the document
        TextSelection selection = document.findString(stringToReplace, false, true);

        // Get the range of the found text
        TextRange range = selection.getAsOneRange();
        int index = range.getOwnerParagraph().getChildObjects().indexOf(range);

        // Insert the image and remove the placeholder text
        range.getOwnerParagraph().getChildObjects().insert(index, pic);
        range.getOwnerParagraph().getChildObjects().remove(range);
    }
}

Output:

Screenshot of the input template file containing placeholders and the output Word document.

Generate a Word Document by Modifying Bookmark Content

This approach uses Word bookmarks to identify locations in the document where content should be inserted or modified. The BookmarksNavigator class in Spire.Doc streamlines the process by enabling direct access to bookmarks, allowing targeted content replacement while automatically preserving the document's original structure and formatting.

Steps to generate Word documents from templates by modifying bookmark content:

  • Initialize Document: A new Document object is initialized.
  • Load the template: The template document with predefined bookmarks is loaded.
  • Set up replacements: A HashMap is created to map bookmark names to their replacement values.
  • Navigate to bookmarks: A BookmarksNavigator is instantiated to navigate through bookmarks in the document.
  • Replace content: The replaceBookmarkContent() method updates the bookmark's content.
  • Save the result: The modified document is saved to a specified path.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.*;
import java.util.HashMap;
import java.util.Map;

public class ModifyBookmarkContent {

    public static void main(String[] args) {

        // Initialize a new Document object
        Document document = new Document();

        // Load the template Word file
        document.loadFromFile("C:\\Users\\Administrator\\Desktop\\template.docx");

        // Define bookmark names and their replacement values
        Map replaceDict = new HashMap<>();
        replaceDict.put("name", "Tech Innovations Inc.");
        replaceDict.put("year", "2015");
        replaceDict.put("headquarter", "San Francisco, California, USA");
        replaceDict.put("history", "Tech Innovations Inc. was founded by a group of engineers and " +
                "entrepreneurs with a vision to revolutionize the technology sector. Starting " +
                "with a focus on software development, the company expanded its portfolio to " +
                "include artificial intelligence and cloud computing solutions.");

        // Create a BookmarksNavigator to manage bookmarks in the document
        BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document);

        // Iterate through the bookmarks
        for (Map.Entry entry : replaceDict.entrySet()) {

            // Navigate to a specific bookmark
            bookmarkNavigator.moveToBookmark(entry.getKey());

            // Replace content
            bookmarkNavigator.replaceBookmarkContent(entry.getValue(), true);
        }

        // Save the modified document
        document.saveToFile("output/ReplaceBookmarkContent.docx", FileFormat.Docx);

        // Release resources
        document.dispose();
    }
}

Output:

Screenshot of the input template file containing bookmarks and the output Word document.

Conclusion

Both methods provide effective ways to generate documents from templates, but they suit different scenarios:

Text Replacement Method is best when:

  • You need simple text substitutions
  • You need to insert images at specific locations
  • You want to replace text anywhere in the document (not just specific locations)

Bookmark Method is preferable when:

  • You're working with complex documents where precise location matters
  • You need to replace larger sections of content or paragraphs
  • You want to preserve bookmarks for future updates

Spire.Doc also offers Mail Merge capabilities, enabling high-volume document generation from templates. This feature excels at producing personalized documents like mass letters or reports by merging template fields with external data sources like databases.

FAQs

Q1: Can I convert the generated Word document to PDF?

A: Yes, Spire.Doc for Java supports converting documents to PDF and other formats. Simply use saveToFile() with FileFormat.PDF.

Q2: How can I handle complex formatting in generated documents?

A: Prepare your template with all required formatting in Word, then use placeholders or bookmarks in locations where dynamic content should appear. The formatting around these markers will be preserved.

Q3: What's the difference between mail merge and text replacement?

A: Mail merge is specifically designed for merging database-like data with documents and supports features like repeating sections for records. Text replacement is simpler but doesn't handle tabular data as elegantly.

Get a Free License

To fully experience the capabilities of Spire.Doc for Java without any evaluation limitations, you can request a free 30-day trial license.