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

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How to Convert HTML to DOCX in Java
  • How To Get and Set PDF Form Fields in Java
  • Jakarta NoSQL 1.0: A Way To Bring Java and NoSQL Together
  • Build a REST API With Just 2 Classes in Java and Quarkus

Trending

  • Apache Doris vs Elasticsearch: An In-Depth Comparative Analysis
  • A Complete Guide to Modern AI Developer Tools
  • Hybrid Cloud vs Multi-Cloud: Choosing the Right Strategy for AI Scalability and Security
  • Internal Developer Portals: Modern DevOps's Missing Piece
  1. DZone
  2. Coding
  3. Java
  4. How to Get Word Document Form Values Using Java

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.

By 
Brian O'Neill user avatar
Brian O'Neill
DZone Core CORE ·
Mar. 25, 25 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
4.4K Views

Join the DZone community and get the full member experience.

Join For Free

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

  1. Unzip the DOCX file
  2. Navigate to the word/ folder
  3. Find the document.xml file
  4. 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:

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:

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

Groovy
 
allprojects {
	repositories {
		...
		maven { url 'https://jitpack.io' }
	}
}


And we’ll then add the dependency in build.gradle:

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

Java
 
// 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):

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

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

JSON
 
{
  "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.

API Form (document) Java (programming language) docx

Opinions expressed by DZone contributors are their own.

Related

  • How to Convert HTML to DOCX in Java
  • How To Get and Set PDF Form Fields in Java
  • Jakarta NoSQL 1.0: A Way To Bring Java and NoSQL Together
  • Build a REST API With Just 2 Classes in Java and Quarkus

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!