Freemarker is a template engine that can generate web pages, emails, documents, and more. For simple Word document exports, writing an ftl template by hand works fine. But for complex documents — ones with intricate styling, headers, footers, embedded images, and annotations — hand-coding templates quickly becomes impractical. Here’s a solution that starts from the target document itself: convert the target Word template to an xml document, then convert the xml to an ftl file, and manually replace the variables in the template. This approach handles documents of any complexity.
2. From Target Document to ftl Template
We’ll use a house rental contract as the example. The template includes landlord info, tenant info, and property details.
Step 1: Convert the Template to xml
In Word, click File → Save As, and choose xml format.
Open the xml file in NotePad++ or Sublime. The raw output is a wall of text with no indentation, so you’ll want to format it first.
Step 2: Convert xml to ftl
After formatting, save the file as ftl. Now comes the manual part — replacing template variables.
Text parameters: Find each placeholder by its default value in the template and replace it directly.
Image parameters: Images are stored as Base64-encoded values in the template. The encoding step is handled by Java.
3. Exporting Word from the ftl Template with Java
Create a freemarker_template folder under Resource and place the ftl file inside.
Important note: Documents exported this way are essentially xml documents under the hood, so you must use the .doc extension. See Inside the docx format for details.
Run the test and the file Rental Contract.doc gets generated.
4. Takeaways
Converting a target template to ftl and then processing it can theoretically handle documents of any complexity. But this approach has a real downside: ftl files end up packed with inline styles and complex tags, making them nearly unreadable. When the template changes, manually replacing a large number of parameters becomes a nightmare.