How to merge two Word DOCX files together in Java

Today’s lightning-fast tutorial covers DOCX merging with Java.

To begin, we must install our library via Jitpack. This requires a pair of references to be added to our pom.xml file.

Repository

<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>

Dependency

<dependencies>
<dependency>
<groupId>com.github.Cloudmersive</groupId>
<artifactId>Cloudmersive.APIClient.Java</artifactId>
<version>v3.34</version>
</dependency>
</dependencies>

With that out of the way, we can invoke mergeDocumentDocx and give it the names of our document files to be merged. These files will be merged in order, making it easy to merge numerous documents in succession.

// Import classes://import com.cloudmersive.client.invoker.ApiClient;//import com.cloudmersive.client.invoker.ApiException;//import com.cloudmersive.client.invoker.Configuration;//import com.cloudmersive.client.invoker.auth.*;//import com.cloudmersive.client.MergeDocumentApi;ApiClient defaultClient = Configuration.getDefaultApiClient();// Configure API key authorization: ApikeyApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");Apikey.setApiKey("YOUR API KEY");// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)//Apikey.setApiKeyPrefix("Token");MergeDocumentApi apiInstance = new MergeDocumentApi();File inputFile1 = new File("/path/to/file"); // File | First input file to perform the operation on.File inputFile2 = new File("/path/to/file"); // File | Second input file to perform the operation on (more than 2 can be supplied).try {byte[] result = apiInstance.mergeDocumentDocx(inputFile1, inputFile2);System.out.println(result);} catch (ApiException e) {System.err.println("Exception when calling MergeDocumentApi#mergeDocumentDocx");e.printStackTrace();}

That’s really all there is to it. Our response will be a DOCX file with the contents of our first two files. If you need some other, similar functionality — such as format conversion and editing — you should take a look at some of our other tutorials.

Image for post
Image for post

Written by

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store