In today’s article, we’ll look at generating a document based on the docx document template. This is a very common task in business applications where you service needs to provide a report to a user based on his actions.
To generate the that document, we will use the docx-stamper library.
First steps
Let’s create a basic maven project.
First we add a maven dependency for using the library
1 2 3 4 5 6 7 |
<dependencies> <dependency> <groupId>org.wickedsource</groupId> <artifactId>docx-stamper</artifactId> <version>1.1.0</version> </dependency> </dependencies> |
Creating docx template
Now you need to create a document to generate the report.
Here’s what I got:
Coding
Now we need to generate a report. First, we need to create a
DocxStamper object and pass
DocxStamperConfiguration there, if you do not know what to transfer in the settings, just create it without specifying the parameters.
To generate the file, the
context is passed.
Context is usually a POJO file that contains all the data for output to the template.
Here is an example of the file I created for this example:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public class DocxContext { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } |
Now let’s see the whole example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
package test.word.report.generate; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.docx4j.openpackaging.exceptions.Docx4JException; import org.wickedsource.docxstamper.DocxStamper; import org.wickedsource.docxstamper.DocxStamperConfiguration; /** * * @author thecodeexamples */ public class GenerateReport { public static void main(String[] args) throws FileNotFoundException, Docx4JException, IOException { DocxStamper stamper = new DocxStamper(new DocxStamperConfiguration()); DocxContext context = new DocxContext(); context.setName("John"); InputStream template = new FileInputStream(new File("template.docx")); OutputStream out = new FileOutputStream("output_template.docx"); stamper.stamp(template, context, out); out.close(); } } |
After running the project, the output_template.docx file will be created, in which the finished report will be created.
This is how it will look:
Here you can download full source code of this example.
How can i generate docx document with more variables? Name, LastName, Adress, Date,
just use more variables 🙂