How to Get Word Document Form Values Using Java
This article discusses how the DOCX file structure stores form fields and values and suggests a few Java APIs that simplify retrieving DOCX form content.
Join the DZone community and get the full member experience.
Join For FreeIn this article, we’ll provide some background about Word DOCX forms and discuss how form values (i.e., form responses) can be programmatically extracted from completed DOCX forms in Java. We’ll discuss the specific way in which form responses are stored in the DOCX file structure and how that impacts a programmatic process aimed at retrieving them.
Towards the end of this article, we’ll learn about a few different APIs we can use to build an expedited DOCX form-value retrieval workflow in Java.
Background: DOCX Forms
Much like PDF, the Word DOCX format provides the option to build custom form fields into a template form document. This option is available when developer mode is enabled in a Word DOCX document; administrators can implement a range of customizable fields, including rich and plain text boxes, checkboxes, dropdown menus, date selections, and more.
Administrators can share DOCX forms with various recipients to collect information; when responses are submitted, a copy of the completed form can be saved, and its response contents can be extracted (either manually or via automated processes).
How Forms Are Structured in DOCX File Format
Like all Open Office XML file types, DOCX files are structured as a series of zipped (ZIP archived) XML files. This is an exceptionally developer-friendly setup (especially when compared with the pre-2007 binary Office file structure). The Open Office XML structure allows us to reach into Office files and follow a standardized XML path to extract just about any content we need independently from other document content.
In any DOCX file archive, we can find all the Word-specific content we need in the word/
folder within the document.xml
file (this includes text, formatting, and embedded elements — including form fields).
DOCX form fields are specifically represented as “content controls”, and these can be found in <w:sdt>
(Structured Document Tag) elements in the word/document.xml
file. Each <w:sdt>
contains a nested <w:sdtPr>
element defining the properties and settings of a given content control, a <w:docPartObj>
defining the “type” or “gallery” of the content control, and a <w:docPartGallery w:val= “”/>
, where w:val=
is set to the specific type of content the content control in question expects (e.g., w:val=“Text”
for a text field). The <w:sdtContent>
element contains the actual content in any given control, i.e., the placeholder text or the user-entered data.
Automating Form Content Retrieval in Java
Given what we know about the DOCX file structure, getting DOCX form responses is relatively straightforward. Our programmatic process must:
- Unzip the DOCX file
- Navigate to the
word/
folder - Find the
document.xml
file - Select
<w:sdtContent>
The only thing standing in our way is the implementation of actual Java code to satisfy that process. While coding this workflow from scratch might make for a fun Java side-project, it’s a bit less practical under the time constraints of most production environments. Thankfully, we can lean on a few different API solutions to expedite our own implementation.
Open-Source API for DOCX Form Content Retrieval
As far as open-source options go, Apache POI remains the strongest recommendation (we’ve suggested this library a lot in past articles).
With Apache POI, we can represent our DOCX content with the XWPFDocument
class, retrieve <w:sdt>
elements with the XWPFSDT
class, check for different field types in the resulting list (e.g., text, checkbox, checkdown, etc.), and call various methods like isChecked()
(for checkbox fields) and getText()
(for text-based fields) to extract form submission values.
Fully Realized Web API Solution
If we’re looking for a quick, plug-and-play option with less documentation-reading involved (not to mention less memory consumption in our environment), we can use a free web API to get the job done instead. This option will abstract file processing away from our environment and return a simple, neatly structured response body containing an array of all the content control values present in a given DOCX form.
Below, we’ll walk through each step required to call this API.
We’ll start by installing the SDK. If we’re installing with Maven, we’ll add the following reference to the repository in pom.xml
:
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
Next, we’ll add the following reference to the dependency in pom.xml
:
<dependencies>
<dependency>
<groupId>com.github.Cloudmersive</groupId>
<artifactId>Cloudmersive.APIClient.Java</artifactId>
<version>v4.25</version>
</dependency>
</dependencies>
If we’re installing with Gradle, we’ll add the following to our root build.gradle
(at the end of repositories):
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
And we’ll then add the dependency in build.gradle
:
dependencies {
implementation 'com.github.Cloudmersive:Cloudmersive.APIClient.Java:v4.25'
}
With installation out of the way, we’ll add the import classes at the top of our file:
// 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.EditDocumentApi;
Next, we’ll implement some code to handle configuration and authorization (we’ll need a free API key to authorize our requests):
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");
Finally, we’ll create an instance of the EditDocumentAPI
, create a file input, and implement a try/catch block to make our API call:
EditDocumentApi apiInstance = new EditDocumentApi();
File inputFile = new File("/path/to/inputfile"); // File | Input file to perform the operation on.
try {
GetDocxGetFormFieldsResponse result = apiInstance.editDocumentDocxGetFormFields(inputFile);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling EditDocumentApi#editDocumentDocxGetFormFields");
e.printStackTrace();
}
We can expect our response to follow the below model:
{
"Successful": true,
"ContentControls": [
{
"Value": "string"
}
],
"HandlebarFormFields": [
{
"FormFieldTitle": "string"
}
]
}
We’ll notice two separate arrays in the above model — one for “ContentControls”
and one for “HandlebarFormFields”
. We’re only interested in the “ContentControls”
values in the context of this article, but it’s worth noting that the “HandlebarFormFields”
array will return any form fields structured as {{enter_value}}
in our DOCX form.
The double curly bracket structure is referred to as a handlebar form; this option is sometimes used for programmatic text-replacement workflows (e.g., when web form responses are passed to a DOCX file and content controls are unnecessary).
After we return our content control value array, we can iterate values over any data type and dynamically store response data.
Conclusion
In this article, we discussed DOCX forms and how form values (responses) can be programmatically accessed from the DOCX file structure. We suggested open-source and non-open-source API solutions to simplify the implementation of form value retrieval in a Java environment.
Opinions expressed by DZone contributors are their own.
Comments