docx4j

docx4j from GitHub in Eclipse – 3 years on

June 16th, 2015 by Jason

In May 2012 we posted docx4j-from-github-in-eclipse. That was more than 3 years ago now, so its about time to update that walkthrough 🙂

This post is about getting the docx4j source code setup in Eclipse, so you can not just use it, but easily study it as well (and submit pull requests!).  If you have no interest or need to do that, please see hello-maven-central (if you’re already using a recent Eclipse, you can start at step 4) and/or docx4j-3-0-and-maven (but do use our current version 3.2.x)

Preliminaries – JDK

Make sure you have the JDK installed; Java 6 or later.  The JRE alone is not enough, since it doesn’t include a compiler (javac).

Preliminaries – Eclipse

Install Eclipse.  These days, the basic package has everything you need (ie git and maven support):

Git & GitHub

GitHub is docx4j’s authoritative source repository.  Eclipse now includes a git client. (If you have an older Eclipse, you can install eGit) However, it is still handy to have other git clients installed:

  • on Linux (listed first, given git’s provenance), install git using your distribution’s package manager
  • on Windows, the Git BASH shell is handy; as is Atlassian’s SourceTree
  • on OSX, ditto

Clone or Fork?

With Git, there is a difference between cloning and forking.

  • Cloning gives you a copy of the source code you can work on, but without more, no easy way to contribute changes back.
  • Forking sets you up with the source code, and makes it easy to contribute changes back.

If you think you might be making changes to the docx4j source code, you’re probably best to create a fork on GitHub right from the start.

To create a fork, log in to GitHub, visit https://github.com/plutext/docx4j then press the “Fork” button.

Choose your poison

There are 3 steps to installing docx4j:

  1. clone the docx4j repo
  2. install its dependencies
  3. install docx4j project in Eclipse

You can do these 3 steps entirely within Eclipse, but Eclipse by default doesn’t give much feedback as to what its doing, so you might wonder whether its still working properly.

Since its just as easy (or easier) to use the command line, I’ll show that way first:-

Command Line Approach

To do it this way, you’ll need:

  • a git shell, and
  • Maven

Both of these are worth having in any case.

Step 1. To clone docx4j from your git shell, use the github URL for docx4j (your fork or Plutext’s):

$ git clone -b master –single-branch https://github.com/plutext/docx4j docx4j
Cloning into ‘docx4j’…
remote: Counting objects: 42008, done.
remote: Compressing objects: 100% (58/58), done.
remote: Total 42008 (delta 23), reused 7 (delta 0), pack-reused 41946
Receiving objects: 100% (42008/42008), 61.03 MiB | 128.00 KiB/s, done.
Resolving deltas: 100% (25108/25108), done.

You should now have a docx4j directory, containing the docx4j source code.

Step 2. Next, to get docx4j’s dependencies, you’ll need Maven.

So first, install Maven (if you don’t have it already).  Please see the instructions at maven.apache.org (actually, you’ve already got Maven in Eclipse, but its a bit hard to use from the command line).

Now you can go into your docx4j directory, and type:

mvn install -DskipTests=true

You’ll see Maven download docx4j’s dependencies.

Step 3. Now you are ready to start Eclipse.

Because docx4j includes Eclipse project definition files, you can import the docx4j project.

From the File menu, click Import, then Existing Projects into Workspace:

Browse to your docx4j directory:

Then click Finish.

Now the project should be set up correctly.  If you see errors, please refer further below for troubleshooting.

Eclipse only approach

Step 1. clone the docx4j git repo in Eclipse; for this you need the Git Repositories View:

Window > Show View > Other > Git > Git Repositories View

Click “Clone a Git repository” then enter the URI for docx4j (your fork, or Plutext’s), then click Next.

The master branch is probably all you need (though Eclipse will probably fetch all the others at some point anyway!)

Step 2. On the next screen, you can tick “Import all existing projects after clone finishes“.  (if you don’t do that, you’ll have to manually File > Import, then Existing Projects into Workspace, as explained above)

Step 3. Eclipse will now start building the project; first Maven will get the dependencies.

This may take a while … to see what Eclipse is doing while it displays the status “Building workspace”, from the Console view, click the drop down to see the Maven Console:

There you can watch it downloading stuff.

You can also look at the Progress view.

When its all done, you should have a docx4j project there and ready to go!

Troubleshooting

I don’t cover issues with git clone or maven here; just issues with Eclipse.

If Eclipse has a problem with your docx4j project, you’ll see an exclamation mark:

You can see further info in the Problems view; the most likely problem is that your Java is misconfigured:-

To fix this, on the docx4j project, click Alt-Enter to go into its properties.

Then click Java Build Path, then the Libraries tab.

Do you see a red cross next to JRE System Library, as above?

If so click on the JRE System Library entry to select it, then click the Remove button.

Next click Add Library, the JRE System Library, then add one (1.6 or above).

Note the warning:

That’s OK, we changed the JRE on the Java Build Path up above.

Hello World

Now you are ready to run some docx4j code.

A good place to start is to run  CreateWordprocessingMLDocument

Use docx4j in your own project

To use docx4j in your own project, there are 2 approaches:

  • the Maven way.  If you’re planning to use Maven, you just specify docx4j as a dependency, and if the version matches (look in pom.xml), it’ll use your docx4j project (assuming workspace resolution is switched on).  Please see hello-maven-central (if you’re already using a recent Eclipse, you can start at step 4) and/or docx4j-3-0-and-maven (but do use the version specified in pom.xml)
  • or, via the Java Build Path > Projects tab.

Hello Maven Central

October 29th, 2011 by Jason

With version 2.7.1, docx4j – a library for manipulating Word docx, Powerpoint pptx, and Excel xlsx xml files in Java – and all its dependencies, are available from Maven Central.

This makes it really easy to get going with docx4j.  With Eclipse and m2eclipse installed, you just add docx4j, and you’re done.  No need to mess around with manually installing jars, setting class paths etc.

This post demonstrates that, starting with a fresh OS (Win 7 is used, but these steps would work equally well on OSX or Linux).

Step 1 – Install the JDK

For the purposes of this article, I used JDK 7, but docx4j works with Java 6 and 1.5.

Step 2 – Install Eclipse Indigo (3.7.1)

I normally download the version for J2EE developers. Unzip it and run eclipse

Step 3 – Install m2eclipse.

In Eclipse, click Help > Install New Software.

Type “http://download.eclipse.org/technology/m2e/releases” in the “Work with” field as shown:

then follow the prompts.

Step 4 – Create your Maven project

In Eclipse, File > New > Project.., then choose Maven project

You should see:

Check “Create a simple project (skip archetype selection)” then press next.

Allocate group and artifact id (what you choose as your artifact id will become the name of your new project in Eclipse):

Press finish

This will create a project with directories using Maven conventions:

(Note: If your starting point is a new or existing Java project in Eclipse, you can right click on the project, then choose Configure > Convert to Maven project)

Step 5 – Add docx4j to your POM

Double Click on pom.xml

Next click on the dependencies tab, then click the “add dependency” button, and enter the docx4j coordinates as shown in the image below:

The result is this pom:


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>mygroup</groupId>
  <artifactId>myartifact</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <dependencies>
  	<dependency>
  		<groupId>org.docx4j</groupId>
  		<artifactId>docx4j</artifactId>
  		<version>2.7.1</version>
  	</dependency>
  </dependencies>
</project>

Ctrl-S to save it.

m2eclipse may take some time to download the dependencies.

When it has finished, you should be able to see them:

Step 6 – Create HelloMavenCentral.java

If you made a Maven project as per step 4 above, you should already have src/main/java on your build path.

If not, create the folder and add it.

Now add a new class:

import org.docx4j.openpackaging.packages.WordprocessingMLPackage;

public class HelloMavenCentral {

	public static void main(String[] args) throws Exception {
		
		WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();
		
		wordMLPackage.getMainDocumentPart()
			.addStyledParagraphOfText("Title", "Hello Maven Central");

		wordMLPackage.getMainDocumentPart().addParagraphOfText("from docx4j!");
				
		// Now save it 
		wordMLPackage.save(new java.io.File(System.getProperty("user.dir") + "/helloMavenCentral.docx") );
		
	}	
}

Step 7 – Click Run

When you click run, all being well, a new docx called helloMavenCentral.docx will be saved.

You can open it in Word (or anything else which can read docx), or unzip it to inspect its contents.

Step 8 – Adding docx4j.properties

One final thing. If you plan on creating documents from scratch using docx4j, it is useful to set paper size etc, via docx4j.properties. Put something like the following on your path:

# Page size: use a value from org.docx4j.model.structure.PageSizePaper enum
# eg A4, LETTER
docx4j.PageSize=LETTER
# Page size: use a value from org.docx4j.model.structure.MarginsWellKnown enum
docx4j.PageMargins=NORMAL
docx4j.PageOrientationLandscape=false

# Page size: use a value from org.pptx4j.model.SlideSizesWellKnown enum
# eg A4, LETTER
pptx4j.PageSize=LETTER
pptx4j.PageOrientationLandscape=false

# These will be injected into docProps/app.xml
# if App.Write=true
docx4j.App.write=true
docx4j.Application=docx4j
docx4j.AppVersion=2.7.1
# of the form XX.YYYY where X and Y represent numerical values

# These will be injected into docProps/core.xml
docx4j.dc.write=true
docx4j.dc.creator.value=docx4j
docx4j.dc.lastModifiedBy.value=docx4j

#
#docx4j.McPreprocessor=true

# If you haven't configured log4j yourself
# docx4j will autoconfigure it.  Set this to true to disable that
docx4j.Log4j.Configurator.disabled=false

And that’s it. For more information on docx4j, see our Getting Started document.

Please click the +1 button if you found this article helpful.