DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • How to Convert a PDF to Text (TXT) Using Java
  • How To Perform OCR on a Photograph of a Receipt Using Java
  • How to Merge HTML Documents in Java
  • How to Get Plain Text From Common Documents in Java

Trending

  • MCP Servers: The Technical Debt That Is Coming
  • GitHub Copilot's New AI Coding Agent Saves Developers Time – And Requires Their Oversight
  • Scaling Microservices With Docker and Kubernetes on Production
  • Rust, WASM, and Edge: Next-Level Performance
  1. DZone
  2. Data Engineering
  3. Databases
  4. How to Merge DOCX Files and Replace Text Strings in Java

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.

By 
Brian O'Neill user avatar
Brian O'Neill
DZone Core CORE ·
Oct. 15, 20 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
9.3K Views

Join the DZone community and get the full member experience.

Join For Free

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 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: 

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 a 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, MergeDocumentDocx. For 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:  

  • 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: 

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. 

Java (programming language) Merge (version control) Strings Document API

Opinions expressed by DZone contributors are their own.

Related

  • How to Convert a PDF to Text (TXT) Using Java
  • How To Perform OCR on a Photograph of a Receipt Using Java
  • How to Merge HTML Documents in Java
  • How to Get Plain Text From Common Documents in Java

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!