Creating Word docx documents dynamically from Grails (or Java :-)


I’m presently working on a little side project that needs to generate a bunch of customisable client reports. One format of interest to our target market is the ubiquitous Word document. Now I know that Word switched to an zipped XML format a while back, so it’s given me a chance to do some researching into what Java libraries might exist for creating and editing the Word xml format.

I’ve played with Apache POI before, but it’s Word support for the latest gear is a little scratchy, so I figured I would hunt around for an nice libraries that people have built for handling the new XML format natively. I didn’t have to hunt far to discover the conveniently named docx4j.

This library gives you everything you need to create/load/edit/write Word docx documents from Java, and comes with a Maven repo, online Javadoc, and nice set of Sample code. What more could you ask for? :-)

But I’m sure you’re just keen to see how to use it in your Grails app, right? Enough talk… First you’ll need to add a couple of entries to your /grails-app/conf/BuildConfig.groovy to make sure you pull in the dependencies. In the extract below, I’ve added a couple of new repos, and the dependency to pull in the docx4j jars:

    repositories {

        // uncomment the below to enable remote dependency resolution
        // from public Maven repositories

        // Details from docx4j Getting Started Guide at http://dev.plutext.org/svn/docx4j/trunk/docx4j/docs/Docx4j_GettingStarted.html
        mavenRepo "http://dev.plutext.org/svn/docx4j/trunk/docx4j/m2"
        mavenRepo "https://webdavclient4j.svn.sourceforge.net/svnroot/webdavclient4j/trunk/m2"
    dependencies {
        compile 'org.docx4j:docx4j:2.5.0'

With all our dependencies in place, we’ll just need to create some controller action that generates our Word document and sends it back to the client. I’m going to show one that queries my Asset class to pull back a set of assets and dump them in a Word doc:

  import org.docx4j.openpackaging.packages.WordprocessingMLPackage

  def exportWord = {
    WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage()
    def mainPart = wordMLPackage.getMainDocumentPart()

    // create some styled heading...
    mainPart.addStyledParagraphOfText("Title", "Asset Library")
    mainPart.addStyledParagraphOfText("Subtitle", "Generated at " + Calendar.getInstance().getTime().toString())

    // Add our list of assets to the document
    Asset.list().each { asset ->

    // write out our word doc to disk
    File file = File.createTempFile("wordexport-", ".docx")
    wordMLPackage.save file

    // and send it all back to the browser
    response.setHeader("Content-disposition", "attachment; filename=assets.docx");
    response.outputStream << file.readBytes()


With our document sent, the user can fire it up from their browser window. Here's a sample of the output from above:

There are tons of things you can do with customising the documents in memory. I'll be doing some work importing Word templates, customising their fields, then exporting the finished product to the browser. Fun times ahead!

Enjoy your docx generating!

10 Responses to “Creating Word docx documents dynamically from Grails (or Java :-)”

  1. Donal says:

    Where are the styles that are applied to “Title”, “Subtitle”, etc. defined, within the library?

  2. Glen Smith says:

    Hi Donal, I think the styles are just the built in Word styles.

    They are not part of the Java library itself – Word just renders the named styled text in whatever that style is set to in Word.

  3. @Donal, @Glen Smith


    The styles are the built-in styles available in MS Word, but you can define your own styles too. “Normal” is the default and apart from “Title” and “Subtitle”, you can also find “Heading 1″, “Heading 2″, … for headings.

  4. John says:

    Cheers Glen, I too need to make the change from doc to docx, this library looks sweet. I’ve only used POI for .xls and with a few wrappers is nice enough but his looks great!

  5. Amarjeet Chauhan says:

    Hi Glen,
    I have one query. I have a String in java for ex String str = “Tested by achauhan” ; This is a html value . I want to write this value into doc file using java. but i am not getting any to do this.
    I am trying docx4j api with jsoup but i did not get any result yet. Do you have any idea about this. I have searched a lot about it but did not get any thing useful. Please share you knowledge if you can help me with this. :)

    Thanks & Regards

  6. lee says:

    I want to draw some tables with content in them. What API would support table operation? Thanks!

  7. pratik says:

    with this api how could we insert an image in word file.

  8. chisi says:

    i may suppose to install docx4j to display MS word in eclipse. because each time i try to sysout a imported MS word file in eclipse it crushes. help!

  9. Angel Alberici says:

    Thank you very much, I will tried ASAP;

    By the way, the library doesn’t exist with Grails 2.3.5.
    The easiest solution I tought:
    1. Go to docx4j, download the jar
    2. Clean your project
    3. Copy the jar in the projectFolder->lib
    4. Right-click on the project and choose Groovy Tools -> Refresh Dependencies

  10. Angel Alberici says:

    Hoho, now is working :) Thank you very much (again!)

    For newbies like me in Grails, remember to add the doc mime type support:


    grails.mime.types = [
    docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Powered by WordPress | Designed by Elegant Themes