Skip to content

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

License

Notifications You must be signed in to change notification settings

verronpro/docx-stamper

Repository files navigation

OfficeStamper

Introduction

OfficeStamper (formerly Docx-Stamper) is a Java template engine that allows for dynamic creation of docx documents at runtime. You design a template using your preferred Word processor; and OfficeStamper will generate documents based on that template.

Build Status Build Status Build Status Build Status

Release Notes

  • v2.1.0:

    • Update Readme howto to document the last API changes

    • Update the mechanism to walk through a Word document

    • First step to the separation of resolvers in two: the future 'engine resolver' (that will wrap the template features) and 'context resolver' (that will wrap the actual stamped data)

    • Update exception management and messages

    • The raw stamper does not carry any comment processors by default

    • Bump dependencies org.springframework:spring-expression to 6.1.8

    • Update documentation to be more Github-friendly

  • v2.0.1:

    • fix dependency issue of v2.0

  • v2.0.0:

    • remove legacy APIs,

    • rename pro.verron:docx-stamper to pro.verron.office-stamper:engine

    • implements modularization

  • v1.6.9: regression fix

  • v1.6.8:

    • new APIs,

    • move toward modularization

    • new experimental namespace for beta features

  • v1.6.7:

    • ObjectResolver to replace ITypeResolver,

    • null stamping behavior become a standard behavior managed by specific ObjectResolver implementations,

    • introduce the preset namespace to hold default configurations of the engine

    • engine can now run without a default resolver, in that case it will throw an exception when it needs to find a resolver.

Usage

Here is a simple code snippet exemplifying how to use OfficeStamper:

class Example {
    public static void main(String[] args) {
        // your own POJO against which expressions found in the template will be resolved
        var context = new YourPojoContext(_, _ , _);

        // an instance of the stamper
        var stamper = OfficeStampers.docxStamper();

        try(
            // Path to your .docx template file
            var template = Files.newInputStream(Paths.get("your/docx/template/file.docx"));
            // Path to write the resulting .docx document
            var output = Files.newOutputStream(Paths.get("your/desired/output/path.docx"))
        ) {
            stamper.stamp(template, context, output);
        }
    }
}

Template Expressions and Their Usage

The foundation of OfficeStamper lies in its ability to replace expressions within the text of a .docx template document. Conveniently, add expressions such as ${person.name} or ${person.name.equals("Homer") ? "Duff" : "Budweiser"} in the text of the .docx file you’re using as a template. Then, provide a context object to resolve the placeholder. Don’t worry about formatting, OfficeStamper will maintain the original text’s formatting in the template. You have full access to the extensive feature set of Spring Expression Language (SpEL).

Resolvers Order

Default Resolvers When the placeholder resolves to a It will be replaced in the document with

Resolvers.image()

pro.verron.officestamper.preset.Image

an inline image

Resolvers.legacyDate()

java.util.Date

a formatted Date string (default "dd.MM.yyyy")

Resolvers.isoDate()

java.time.LocalDate

a formatted Date string (default DateTimeFormatter.ISO_LOCAL_DATE)

Resolvers.isoTime()

java.time.LocalTime

a formatted Date string (default DateTimeFormatter.ISO_LOCAL_TIME)

Resolvers.isoDateTime()

java.time.LocalDateTime

a formatted Date string (default DateTimeFormatter.ISO_LOCAL_DATE_TIME)

Resolvers.nullToEmpty()

null

an empty string

Resolvers.fallback()

Object

the result of the call to String.valueOf() method on the object

If a placeholder fails to resolve successfully, OfficeStamper will skip it, the placeholder in the document remains the same as its initial state in the template.

Comment Processors

Alongside expression replacement, Office-Stamper presents the feature of processing comments associated with paragraphs in your .docx template. These comments act as directives for manipulating the template. As a standard, the following expressions can be used within comments:

Table 1. Default activated comment processors

Expression in .docx comment

Effect on the commented paragraph/paragraphs

displayParagraphIf(boolean)

It is only displayed if condition resolves to true.

displayTableRowIf(boolean)

The table row around it is only displayed if condition resolves to true.

displayTableIf(boolean)

The whole table around it is only displayed if condition resolves to true.

repeatParagraph(List<Object>)

It is copied once for each object in the passed-in list. Expressions found in the copies are evaluated against the object from the list.

repeatTableRow(List<Object>)

The table row around it 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>)

It is copied once for each object in the passed-in list. Expressions found in the copies are evaluated against the object from the list. Can be used instead of repeatTableRow and repeatParagraph if you want to repeat more than table rows and paragraphs.

replaceWordWith(expression)

Replace the commented word with the value of the given expression.

resolveTable(StampTable)

Replace a table (that must have one column and two rows) with the values given by the StampTable. The StampTable contains a list of headers for columns, and a 2-level list of rows containing values for each column.

By default, an exception is thrown if a comment fails to process. However, successfully processed comments are wiped from the document.

Custom settings

Custom resolvers

You can expand the resolution functionality by implementing custom ObjectResolver.

Here’s a code snippet on how to proceed:

class Main {
    public static void main(String... args) {
        // instance of your own ObjectResolver implementation
        var customResolver = new StringResolver(YourCustomType.class){
            @Override public String resolve(YourCustomType object){
                return doYourStuffHere(); // this is your implementation detail
            }
        };

        var configuration = OfficeStamperConfigurations.standardWithPreprocessing();
        configuration.addResolver(resolver);

        var stamper = OfficeStampers.docxStamper(configuration);
    }
}

Custom functions

OfficeStamper lets you add custom functions to the tool’s expression language. For example, if you need specific formats for numbers or dates, you can register such functions which can then be used in the placeholders throughout your template.

Below is a sample code demonstrating how to extend the expression language with a custom function. This particular example adds a function toUppercase(String), enabling you to convert any text in your .docx document to uppercase.

class Main {
    public static void main(String... args) {
        interface UppercaseFunction {
            String toUppercase(String string);
        }

        var configuration = OfficeStamperConfigurations.standardWithPreprocessing();
        configuration.exposeInterfaceToExpressionLanguage(UppercaseFunction.class, String::toUppercase);
        var stamper = OfficeStampers.docxStamper(configuration);
    }
}

Chains of such custom functions can enhance the versatility of OfficeStamper, making it capable of handling complex and unique templating situations.

Custom Comment Processors

For additional flexibility, create your own expression within comments by implementing your ICommentProcessor.

Here’s an example of how to create and register a custom comment processor:

class Main {
    public static void main(String... args) {
        // interface defining the methods to expose to the expression language
        interface IYourCommentProcessor {
            void yourComment(String _); // 1+ argument of the type you expect to see in the document
            void yourSecondComment(String _, CustomType _); // theoretically, any number of comment can be added
        }
        class YourCommentProcessor extends BaseCommentProcessor {
            @Override public void commitChanges(WordprocessingMLPackage document) {/*Do something to the document*/}
            @Override public void reset() {/* reset processor state for re-run of the stamper */}
        }
        var commentProcessor = new YourCommentProcessor();
        var configuration = new DocxStamperConfiguration()
                .addCommentProcessor(IYourCommentProcessor.class, commentProcessor);
        var stamper = OfficeStampers.docxStamper(configuration);
    }
}

Custom SpEL Evaluation Context

At times, you might want to exert more control over how expressions are evaluated. With Office-Stamper, there’s provision for such scenarios. Here’s how:

Implement your own EvaluationContextConfigurer. This allows you to customize Springs StandardEvaluationContext according to your requirements.

Here’s a code snippet on how to proceed:

import org.springframework.context.expression.MapAccessor;
class Main {
    public static void main(String... args) {
        var configuration = OfficeStamperConfigurations.standardWithPreprocessing();

        // explicitly set the default configurer, that only allows a subset of SpEL features
        configuration.setEvaluationContextConfigurer(EvaluationContextConfigurers.defaultConfigurer());

        // or choose the more full-featured but potentially unsafe noopConfigurer
        configuration.setEvaluationContextConfigurer(EvaluationContextConfigurers.noopConfigurer());

        // or call other sources, like MapAccessor from org.springframework.context, that allow resolving Map objects
        configuration.setEvaluationContextConfigurer(ctx -> ctx.addPropertyAccessor(new MapAccessor()));

        var stamper = OfficeStampers.docxStamper(configuration);
    }
}

This feature empowers you with greater flexibility and enhanced control over the expression evaluation process, fitting Office-Stamper seamlessly into complex scenarios and requirements.

Conditional and Repetitive Displays within Headers and Footers

The .docx file format does not permit comments within headers or footers. But there’s a workaround in OfficeStamper. If you want to display contents within headers or footers conditionally, or require repetitive elements, all you got to do is :

  1. Craft the expression as you would in a comment.

  2. Encapsulate it with "#{}".

  3. Position it at the starting of the paragraph you intend to manipulate.

The assigned expression will be processed in the same way it would be in a comment, allowing you to maximize template customization.

Remember, this workaround unlocks the power of conditional display and repetition in your document’s headers and footers, enhancing document dynamics.

Graceful Error Handling

In general, DocxStamper employs an OfficeStamperException if there’s a failure in resolving an expression within a document or the associated comments. However, you can modify this behavior.

Follow the given example to silence the exception and keep OfficeStamper from failing even when it encounters unresolved expressions:

class Main {
    public static void main(String... args) {
        var configuration = OfficeStamperConfiguration.standardWithPreprocessing()
                .setFailOnUnresolvedExpression(false);
        var stamper = OfficeStampers.docxStamper(configuration);
    }
}

This customization allows you to control the failure behavior of DocxStamper according to your specific requirements.

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 mvn test with the system property -DkeepOutputFile=true so that the resulting .docx documents will not be cleaned up and let you 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 sources 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: go to last documented version

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>11.4.11</version>
</dependency>

This way, you can choose which version of Docx4J you want to use instead of having it dictated by docx-stamper.

The list of actively integrated docx4j is listed here → Docx4J integration matrix]

Contribute

If you have an issue or create 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.