Skip to main content

Generate Word Documents in Spring Boot

This guide will show you how to create DOCX files from plain DOCX files with placeholders in 5 minutes using Spring Boot and DocStencil.

1. Add the Dependency

<dependency>
<groupId>com.docstencil</groupId>
<artifactId>docstencil-core</artifactId>
<version>0.2.1</version>
</dependency>

2. Create a Template

Download the welcome-letter.docx template file or create it yourself using Microsoft Word or LibreOffice:

Wwelcome-letter.docx
{$format(date, "MMMM d, yyyy")}

Dear {name},

Welcome to {company}! We're excited to have you on board.

Best regards,
The {company} Team

Save it to src/main/resources/templates/welcome-letter.docx.

3. Create a Service

@Service
class DocumentService {

private val template = OfficeTemplate.fromResource("templates/welcome-letter.docx")

fun generateWelcomeLetter(name: String, company: String): ByteArray {
return template.render(mapOf(
"name" to name,
"company" to company,
"date" to LocalDate.now()
)).toByteArray()
}
}

Templates are thread-safe. You can load them once and then reuse them everywhere.

4. Add a REST Endpoint

@RestController
@RequestMapping("/api/documents")
class DocumentController(private val documentService: DocumentService) {

@GetMapping("/welcome")
fun generateWelcome(
@RequestParam name: String,
@RequestParam company: String
): ResponseEntity<ByteArray> {
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"welcome.docx\"")
.contentType(MediaType.parseMediaType(
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"))
.body(documentService.generateWelcomeLetter(name, company))
}
}

5. Test It

curl "http://localhost:8080/api/documents/welcome?name=Alice&company=Acme" -o welcome.docx

Open welcome.docx to see that your placeholders are replaced with real values.

Full Source Code

View the complete working example on GitHub:

Next Steps