How to Merge DOCX Files and Replace Text Strings in Java

Microsoft Word is one of the most recognized and utilized word processing programs across all demographics and is often the default formatted-text software for business use.  With the ability to easily format and edit text files of any type or length, a wide variety of document genres can be created with basic user knowledge.  

When working with multiple documents simultaneously, however, it may be useful to combine two or more files to create a longer file containing all the necessary information for your needs. For example, if you are building a documentation report detailing your services or organizing contract packets for potential partners, different pieces may be stored in separate files. This means that you will then need to go through each file and manually add the content into a master document file. With this comes possible issues with formatting compatibility and accidental, unwanted editing or erasure of text. 

Rather than attempting to copy each separate file to create your document, the following Convert APIs will allow you to merge DOCX files instantly while maintaining formatting. We will begin by looking at our process for combining two files into one. Then, we will go over how you can add more input files to create much longer and more complex documents for bigger projects. Then, we will show you how to replace text strings within the final Word document to aid in adding user input such as names, dates, and other variable information. This will allow you to create templates to be used recurrently, decreasing the time spent on organizing and parsing your files.  

Our goal with this tutorial is to allow your business to share information and documentation more easily with your clients and partnersFollowing these steps will not only boost your time to deliverable but also improve your organization’s overall standardization and interfacing.  

Our first move for all of these APIs will be to install our SDKs with Maven. To do this, we will add a Jitpack reference to the repository in pom.xml: 

XML
 




xxxxxxxxxx
1


 
1
<repositories>
2
    <repository>
3
        <id>jitpack.io</id>
4
        <url>https://jitpack.io</url>
5
    </repository>
6
</repositories>



Then, we can add a reference to the dependency:  

XML
 




xxxxxxxxxx
1


 
1
<dependencies>
2
<dependency>
3
    <groupId>com.github.Cloudmersive</groupId>
4
    <artifactId>Cloudmersive.APIClient.Java</artifactId>
5
    <version>v3.54</version>
6
</dependency>
7
</dependencies>



After this we can begin calling our functions, starting with two-document merge. To do this, you’ll first need to add the imports to the top of the file.   

Java
 




xxxxxxxxxx
1


1
// Import classes:
2
//import com.cloudmersive.client.invoker.ApiClient;
3
//import com.cloudmersive.client.invoker.ApiException;
4
//import com.cloudmersive.client.invoker.Configuration;
5
//import com.cloudmersive.client.invoker.auth.*;
6
//import com.cloudmersive.client.MergeDocumentApi;



Then, you can call the function, MergeDocumentDocxFor input, you will need to add in the two DOCX files you are wishing to combine  

Java
 




xxxxxxxxxx
1
18


 
1
ApiClient defaultClient = Configuration.getDefaultApiClient();
2
 
          
3
// Configure API key authorization: Apikey
4
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
5
Apikey.setApiKey("YOUR API KEY");
6
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
7
//Apikey.setApiKeyPrefix("Token");
8
 
          
9
MergeDocumentApi apiInstance = new MergeDocumentApi();
10
File inputFile1 = new File("/path/to/inputfile"); // File | First input file to perform the operation on.
11
File inputFile2 = new File("/path/to/inputfile"); // File | Second input file to perform the operation on (more than 2 can be supplied).
12
try {
13
    byte[] result = apiInstance.mergeDocumentDocx(inputFile1, inputFile2);
14
    System.out.println(result);
15
} catch (ApiException e) {
16
    System.err.println("Exception when calling MergeDocumentApi#mergeDocumentDocx");
17
    e.printStackTrace();
18
}



The response to this function should be a single file that you can then save and use immediately. To ensure that this API works properly, you need to ensure certain requirements are met:  

You may notice a note within this code block stating that more than two files can be supplied. This references our next function, which will allow you to add up to ten input files at once. However, for both functions, it is possible to perform multiple concurrent merges. For example, if you already have a merged document that originated as two or more separate files, you can then use it as one of your input files in the following merge.  

To use our next API, you will once again install the SDK with Maven and add the imports to the top of the file as shown above. Then, you can call the function, MergeDocumentDocxMulti: 

Java
 




x
1
33


1
// Import classes:
2
//import com.cloudmersive.client.invoker.ApiClient;
3
//import com.cloudmersive.client.invoker.ApiException;
4
//import com.cloudmersive.client.invoker.Configuration;
5
//import com.cloudmersive.client.invoker.auth.*;
6
//import com.cloudmersive.client.MergeDocumentApi;
7
 
          
8
ApiClient defaultClient = Configuration.getDefaultApiClient();
9
 
          
10
// Configure API key authorization: Apikey
11
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
12
Apikey.setApiKey("YOUR API KEY");
13
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
14
//Apikey.setApiKeyPrefix("Token");
15
 
          
16
MergeDocumentApi apiInstance = new MergeDocumentApi();
17
File inputFile1 = new File("/path/to/inputfile"); // File | First input file to perform the operation on.
18
File inputFile2 = new File("/path/to/inputfile"); // File | Second input file to perform the operation on.
19
File inputFile3 = new File("/path/to/inputfile"); // File | Third input file to perform the operation on.
20
File inputFile4 = new File("/path/to/inputfile"); // File | Fourth input file to perform the operation on.
21
File inputFile5 = new File("/path/to/inputfile"); // File | Fifth input file to perform the operation on.
22
File inputFile6 = new File("/path/to/inputfile"); // File | Sixth input file to perform the operation on.
23
File inputFile7 = new File("/path/to/inputfile"); // File | Seventh input file to perform the operation on.
24
File inputFile8 = new File("/path/to/inputfile"); // File | Eighth input file to perform the operation on.
25
File inputFile9 = new File("/path/to/inputfile"); // File | Ninth input file to perform the operation on.
26
File inputFile10 = new File("/path/to/inputfile"); // File | Tenth input file to perform the operation on.
27
try {
28
    byte[] result = apiInstance.mergeDocumentDocxMulti(inputFile1, inputFile2, inputFile3, inputFile4, inputFile5, inputFile6, inputFile7, inputFile8, inputFile9, inputFile10);
29
    System.out.println(result);
30
} catch (ApiException e) {
31
    System.err.println("Exception when calling MergeDocumentApi#mergeDocumentDocxMulti");
32
    e.printStackTrace();
33
}



This will help you organize and simplify your documentation projects to increase your efficiency, improve document appearance, and decrease time-to-delivery to your clients.  

Our final API, as shown below, will allow you to take your now merged documents and replace all instances of specific text strings with new input. This means that you can easily change the names, dates, and other variables instantly, without needing to manually parse the document. With this function, you can also specify whether text case should be matched with a default of unmatched case. 

As with the two previous APIs, we will first install our SDK with Maven. However, the next step should differ slightly because the function is a Transformation API, not a Merge API. This will be reflected in the imports as shown here: 

Java
 




xxxxxxxxxx
1


 
1
// Import classes:
2
//import com.cloudmersive.client.invoker.ApiClient;
3
//import com.cloudmersive.client.invoker.ApiException;
4
//import com.cloudmersive.client.invoker.Configuration;
5
//import com.cloudmersive.client.invoker.auth.*;
6
//import com.cloudmersive.client.TransformDocumentApi;



Once you have placed the imports, you can call our final function, TransformDocumentDocxReplace:  

Java
 




xxxxxxxxxx
1
21


 
1
ApiClient defaultClient = Configuration.getDefaultApiClient();
2
 
          
3
// Configure API key authorization: Apikey
4
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
5
Apikey.setApiKey("YOUR API KEY");
6
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
7
//Apikey.setApiKeyPrefix("Token");
8
 
          
9
TransformDocumentApi apiInstance = new TransformDocumentApi();
10
String matchString = "matchString_example"; // String | String to search for and match against, to be replaced
11
String replaceString = "replaceString_example"; // String | String to replace the matched values with
12
File inputFile = new File("/path/to/inputfile"); // File | Optional: Input file to perform the operation on.
13
String inputFileUrl = "inputFileUrl_example"; // String | Optional: URL of a file to operate on as input. This can be a public URL, or you can also use the begin-editing API (part of EditDocumentApi) to upload a document and pass in the secure URL result from that operation as the URL here (this URL is not public).
14
Boolean matchCase = true; // Boolean | Optional: True if the case should be matched, false for case insensitive match. Default is false.
15
try {
16
    byte[] result = apiInstance.transformDocumentDocxReplace(matchString, replaceString, inputFile, inputFileUrl, matchCase);
17
    System.out.println(result);
18
} catch (ApiException e) {
19
    System.err.println("Exception when calling TransformDocumentApi#transformDocumentDocxReplace");
20
    e.printStackTrace();
21
}



This, too, will allow you to decrease project time and allow you to quickly adjust documents to meet deliverable requirements.  

If you have any questions about using these APIs or inquiries concerning other API solutions, you can visit the Cloudmersive website where our team is happy to help with anything you might need. 

 

 

 

 

Top