• Stars
    star
    204
  • Rank 192,063 (Top 4 %)
  • Language
    Java
  • License
    MIT License
  • Created almost 9 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Easy-to-use template engine for creating docx documents in Java.

docx-stamper

Build Status

docx-stamper is a Java template engine for docx documents. You create a template .docx document with your favorite word processor and feed it to a DocxStamper instance to create a document based on the template at runtime. Example code:

MyContext context = ...;                 // your own POJO against which expressions found in the template
                                         // will be resolved
InputStream template = ...;              // InputStream to your .docx template file
OutputStream out = ...;                  // OutputStream in which to write the resulting .docx document
DocxStamper stamper = new DocxStamperConfiguration()
  .build();
stamper.stamp(template, context, out);
out.close();

Replacing Expressions in a .docx Template

The main feature of docx-stamper is replacement of expressions within the text of the template document. Simply add expressions like ${person.name} or ${person.name.equals("Homer") ? "Duff" : "Budweiser"} in the text of your .docx template and provide a context object against which the expression can be resolved. docx-stamper will try to keep the original formatting of the text in the template intact. You can use the full feature set of Spring Expression Language (SpEL).

The value an expression resolves to may be of the following types:

Type of expression value Effect
java.lang.Object The expression is replaced by the String representation of the object (String.valueOf()).
java.lang.String The expression is replaced with the String value.
java.util.Date The expression is replaced by a formatted Date string (by default "dd.MM.yyyy"). You can change the format string by registering your own DateResolver.
org.wickedsource.docxstamper...Image The expression is replaced with an inline image.

If an expression cannot be resolved successfully, it will be skipped (meaning the expression stays in the document as it was in the template). To support more than the above types you can implement your own TypeResolver. To register your own TypeResolver with docx-stamper, use the following code:

ITypeResolver typeResolver = ...;              // instance of your own ITypeResolver implementation
Class<?> type ...;                             // class of expression values your resolver handles
DocxStamper stamper = new DocxStamperConfiguration()
  .addTypeResolver(type, typeResolver)
  .build();

Customizing the SpEL Evaluation Context

If you want to take more control over the evaluation of expressions, you can implement a EvaluationContextConfigurer and customize Springs StandardEvaluationContext to your needs. You can register an EvaluationContextConfigurer like this:

EvaluationContextConfigurer configurer = ...;
DocxStamper stamper = new DocxStamperConfiguration()
  .setEvaluationContextConfigurer(configurer)
  .build();

Adding custom functions to the Expression Language

If you want to create custom functions (for different number formats or different date formats, for example), you can register functions which can then be used in the expression language. The following code for example adds a function toUppercase(String) which can be used within the .docx document to uppercase a String:

DocxStamper stamper = new DocxStamperConfiguration()
  .exposeInterfaceToExpressionLanguage(UppercaseFunction.class, new UppercaseFunctionImpl());
  .build();

public interface UppercaseFunction {
  String toUppercase(String string);
}

public static class UppercaseFunctionImpl implements UppercaseFunction {
  @Override
  public String toUppercase(String string) {
    return string.toUpperCase();
  }
}

Conditional Display and Repeating of Elements

Besides replacing expressions, docx-stamper can process comments on paragraphs of text in the template .docx document and do manipulations on the template based on these comments. By default, you can use the following expressions in comments:

Expression in .docx comment Effect
displayParagraphIf(boolean) The commented paragraph is only displayed in the resulting .docx document if the boolean condition resolves to true.
displayTableRowIf(boolean) The table row surrounding the commented paragraph is only displayed in the resulting .docx document if the boolean condition resolves to true.
displayTableIf(boolean) The whole table surrounding the commented paragraph is only displayed in the resulting .docx document if the boolean condition resolves to true.
repeatTableRow(List<Object>) The table row surrounding the commented paragraph is copied once for each object in the passed-in list. Expressions found in the cells of the table row are evaluated against the object from the list.
repeatDocPart(List<Object>) Repeats the part of the document surrounded by the comment. The document part is copied once for each object in the passed-in list. Expressions found in the elements of the document part are evaluated against the object from the list. Can be used instead repeatTableRow and repeatParagraph if you want to repeat more than table rows and paragraphs.
replaceWordWith(expression) Replaces the commented word (must be a single word!) with the value of the given expression.

If a comment cannot be processed, by default an exception will be thrown. Successfully processed comments are removed from the document. You can add support to more expressions in comments by implementing your own ICommentProcessor. To register you comment processor to docx-stamper, use the following code:

ICommentProcessor commentProcessor = ...;      // instance of your own ICommentProcessor implementation
Class<?> interfaceClass = ...;                 // class of the interface that defines the methods that are
                                               // exposed into the expression language
DocxStamper stamper = new DocxStamperConfiguration()
  .addCommentProcessor(interfaceClass, commentProcessor)
  .build();

For an in-depth description of how to create a comment processor, see the javadoc of ICommentProcessor.

Conditional Display and Repeating of Elements in Headers or Footers

The docx file format does not allow comments in Headers or Footers of a document. To be able to conditionally display content in a header or footer, simply surround the expression you would put in a comment with "#{}" and put it at the beginning of the paragraph you want to manipulate. The expression will be evaluated as it would be in a comment.

Error Handling

By default DocxStamper fails with an UnresolvedExpressionException if an expression within the document or within the comments cannot be resolved successfully. If you want to change this behavior, you can do the following:

DocxStamper stamper = new DocxStamperConfiguration()
  .setFailOnUnresolvedExpression(false)
  .build();

Sample Code

The source code contains a set of tests show how to use the features. If you want to run them yourself, clone the repository and run the tests in the main package with the system property -DkeepOutputFile=true so that the resulting .docx documents will not be cleaned up so you can view them. The resulting files will be stored in your local temp folder (watch the logging output for the exact location of the files).

If you want to have a look at the .docx templates used in the tests, have a look at the resources subfolder in the test folder.

Maven coordinates

To include docx-stamper in your project, you can use the following maven coordinates in your dependency management system:

<repositories>
    <repository>
      <id>jcenter</id>
      <url>https://jcenter.bintray.com/</url>
    </repository>
</repositories>

<dependency>
    <groupId>org.wickedsource.docx-stamper</groupId>
    <artifactId>docx-stamper</artifactId>
    <version>1.4.0</version>
</dependency>

Note that as of version 1.4.0 you have to provide the dependency to your version of Docx4J yourself:

<dependency>
    <groupId>org.docx4j</groupId>
    <artifactId>docx4j</artifactId>
    <version>6.1.2</version>
</dependency>

This way, you can choose which version of Docx4J you want to use instead having it dictated by docx-stamper. Look into the .travis.yml file to see against which versions of Docx4J docx-stamper has been tested.

Changelog

Contribute

If you have an issue or created a comment processor or type resolver that you think deserves to be part of the default distribution, feel free to open an issue or - even better - a pull request with your contribution.

Frequently Asked Questions

See the Frequently Asked Questions wiki page for some answers to recurring questions.

More Repositories

1

code-examples

A collection of code examples from blog posts etc.
Java
2,375
star
2

buckpal

An example approach for implementing a Clean/Hexagonal Architecture
Java
1,663
star
3

diffparser

Parse unified diffs with Java.
Java
71
star
4

clean-timetracker

Example application for implementing a Clean Architecture.
Java
57
star
5

sqs-starter

A Spring Boot Starter to make work with AmazonSQS a breeze.
Java
47
star
6

components-example

A component-based architecture example for a Kotlin-based Spring Boot application.
Kotlin
32
star
7

spring-boot-devtools-gradle-plugin

A Gradle plugin to easiliy configure Spring Dev Tools for your Gradle project
Kotlin
19
star
8

descriptive-logger

A descriptive way of creating meaningful and identifiable log messages.
Java
12
star
9

fortune-cookie-shop

Example application to learn about patterns and antipatterns of production-ready software.
Java
8
star
10

cdc-workshop

A workshop on Consumer-Driven-Contracts
Java
8
star
11

wicket-spring-security-example

Example of integrating Spring security in a Wicket web application.
Java
7
star
12

boxtime-cli

Take control of your time by tracking your time-spending habits.
Kotlin
6
star
13

rapid-highcharts

Code base for a video course on the Highcharts javascript charting library.
JavaScript
5
star
14

accessible-forms-example

Small example showing some steps to create an accessible HTML form.
4
star
15

staticular

Easy, configurable, and robust tool to add user-generated content to your static website.
Java
3
star
16

tracing

Java
3
star
17

github-tester

App to test API requests against the GitHub API.
Kotlin
3
star
18

logunit

Test your logging output from within Unit-Tests.
Java
3
star
19

robot-arena

Java
3
star
20

jira-test

test
2
star
21

deployments-test

2
star
22

osiv-reproducer

Minimal reproducer of an unexpected issue with `spring.jpa.open-in-view` and `JDBCTemplate`
Kotlin
2
star
23

wicket-html5-example

Example of how to create HTML5 element in a Wicket web application.
Java
2
star
24

user-config-test

2
star
25

github-devops-app-repo

2
star
26

lottery

Java
2
star
27

wicket-errorhandling-example

Example of how to handle exceptions in a Wicket web application.
Java
2
star
28

wicket-bean-validation-example

Example of using Bean Validation (JSR 303) in a Wicket web application.
Java
1
star
29

workanizer

Offline Browser App to help you manage your tasks.
JavaScript
1
star
30

wicket-requestmapper-example

Example of Wicket's feature for mapping pages and page parameters to URLs.
Java
1
star
31

java-picocli-native

Java
1
star
32

sleuth-otel

Java
1
star
33

wicket-markuploading-example

Example of how to control the location from which to load the HTML markup in a Wicket web application.
Java
1
star
34

wicket-mdc-example

Example on how to use the MDC logging context with Wicket
Java
1
star
35

wicket-progressbar-example

1
star
36

moduliths

Java
1
star
37

wicket-upload-example

Example of a file upload in a Wicket web application.
Java
1
star
38

kotlin-picocli-native

Kotlin
1
star
39

wicket-resource-serving-example

Example of different methods of serving resource files from a Wicket web application.
Java
1
star
40

checkstyle-playground

playing around with checkstyle
Java
1
star
41

wicked-logviewer

Tool for analyzing and viewing java log files.
Java
1
star
42

wicket-bindgen-example

Example of using the bindgen framework to create refactoring-safe PropertyModels in Wicket web applications.
Java
1
star
43

angular

Sandbox for playing around with AngularJS
1
star
44

jira-test-prod

1
star
45

wicket-events-example

Example of using events to decouple GUI components in a Wicket web application.
Java
1
star
46

sandbox-jpa

Java
1
star
47

pact-react-consumer

JavaScript
1
star
48

staticman-test

Testing staticman
1
star
49

jira-test-dev

1
star
50

jenkins-test

Java
1
star
51

hooked

Version Control System hooks to collect code statistics and send them to arbitrary receivers - extendable by plugins.
Java
1
star
52

ikenga-web

Java
1
star
53

jira-test-local

1
star
54

picocli-kotlin-native-maven

Kotlin
1
star
55

wicket-pageexitwarning-example

Example of how to create a javascript "page exit warning" in a Wicket web application.
Java
1
star