How to Merge DOCX Files and Replace Text Strings in Java
Combine multiple Office Word Documents (docx) into a single document; Instantly find and replace specific text string variables like names and dates.
Join the DZone community and get the full member experience.
Join For FreeMicrosoft 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 partners. Following 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:
xxxxxxxxxx
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
Then, we can add a reference to the dependency:
xxxxxxxxxx
<dependencies>
<dependency>
<groupId>com.github.Cloudmersive</groupId>
<artifactId>Cloudmersive.APIClient.Java</artifactId>
<version>v3.54</version>
</dependency>
</dependencies>
After this we can begin calling our functions, starting with a two-document merge. To do this, you’ll first need to add the imports to the top of the file.
xxxxxxxxxx
// 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;
Then, you can call the function, MergeDocumentDocx. For input, you will need to add in the two DOCX files you are wishing to combine.
xxxxxxxxxx
ApiClient defaultClient = Configuration.getDefaultApiClient();
// Configure API key authorization: Apikey
ApiKeyAuth 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/inputfile"); // File | First input file to perform the operation on.
File inputFile2 = new File("/path/to/inputfile"); // 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();
}
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:
Your input files are valid and not encrypted or password protected
You have input your API Key. This can be retrieved at no cost on the Cloudmersive website, providing 800 monthly calls across our API library.
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:
x
// 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: Apikey
ApiKeyAuth 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/inputfile"); // File | First input file to perform the operation on.
File inputFile2 = new File("/path/to/inputfile"); // File | Second input file to perform the operation on.
File inputFile3 = new File("/path/to/inputfile"); // File | Third input file to perform the operation on.
File inputFile4 = new File("/path/to/inputfile"); // File | Fourth input file to perform the operation on.
File inputFile5 = new File("/path/to/inputfile"); // File | Fifth input file to perform the operation on.
File inputFile6 = new File("/path/to/inputfile"); // File | Sixth input file to perform the operation on.
File inputFile7 = new File("/path/to/inputfile"); // File | Seventh input file to perform the operation on.
File inputFile8 = new File("/path/to/inputfile"); // File | Eighth input file to perform the operation on.
File inputFile9 = new File("/path/to/inputfile"); // File | Ninth input file to perform the operation on.
File inputFile10 = new File("/path/to/inputfile"); // File | Tenth input file to perform the operation on.
try {
byte[] result = apiInstance.mergeDocumentDocxMulti(inputFile1, inputFile2, inputFile3, inputFile4, inputFile5, inputFile6, inputFile7, inputFile8, inputFile9, inputFile10);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling MergeDocumentApi#mergeDocumentDocxMulti");
e.printStackTrace();
}
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:
xxxxxxxxxx
// 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.TransformDocumentApi;
Once you have placed the imports, you can call our final function, TransformDocumentDocxReplace:
xxxxxxxxxx
ApiClient defaultClient = Configuration.getDefaultApiClient();
// Configure API key authorization: Apikey
ApiKeyAuth 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");
TransformDocumentApi apiInstance = new TransformDocumentApi();
String matchString = "matchString_example"; // String | String to search for and match against, to be replaced
String replaceString = "replaceString_example"; // String | String to replace the matched values with
File inputFile = new File("/path/to/inputfile"); // File | Optional: Input file to perform the operation on.
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).
Boolean matchCase = true; // Boolean | Optional: True if the case should be matched, false for case insensitive match. Default is false.
try {
byte[] result = apiInstance.transformDocumentDocxReplace(matchString, replaceString, inputFile, inputFileUrl, matchCase);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling TransformDocumentApi#transformDocumentDocxReplace");
e.printStackTrace();
}
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.
Opinions expressed by DZone contributors are their own.
Comments