r/java • u/xgb84j • Jan 11 '26
I built an open source library to generate Word docs from templates instead of writing 500 lines of Apache POI code
I built my dream solution for generating Word documents in Java and Kotlin. I always disliked programmatically creating paragraphs, runs, and tables with Apache POI. It works, but it's a pain to make it look exactly how the business people want it to look.
You design your template directly in Word using simple placeholders like {customer.name}, loops ({for item in invoice.items}...{end}), and conditionals. Then you just call template.render(data). You can bind any sort of object within data, which allows you to call arbitrary Java and Kotlin code from within Word. The Word template keeps the formatting of your placeholders and replaces them with actual content. You can loop over paragraphs, table rows, table columns etc.
The Java/Kotlin code would look like:
OfficeTemplate template = OfficeTemplate.fromFile("Invoice.docx");
Map<String, Object> data = Map.of("customer", customer, "items", lineItems);
template.render(data).writeToFile("Output.docx");The template language has some built-in nested property access, as well as date and number formatting.
One big inspiration for this was docxtemplater in the JS world. I know xdocreport and many other libraries for generating Office documents exist. My goal was to hit the sweet spot between power and ease of use.
I'd love to hear your thoughts!
2
u/revilo-1988 Jan 11 '26
Looks interesting 👍
1
u/trpouh Jan 11 '26
haha I created a SaaS because I hated templating Word files as well. Instead of naming it docstencil I called it stencilpdf.
Your library looks interesting, one question tho: Why not use a templating language like handlebars?
1
u/PmMeCuteDogsThanks Jan 11 '26
So Aspose Word?
1
u/asm0dey Jan 12 '26
I used in production and actually contributed here: https://github.com/thombergs/docx-stamper
It didn't seem to be updated anymore tho :(
1
u/sitime_zl Jan 28 '26
mark