How to Convert HTML to Office Word Document (DOCX) Format

Cloudmersive
2 min readSep 7, 2022

--

It’s a bit more common to convert HTML strings to PDF format given the universal interoperability of PDF documents. But that doesn’t mean it can’t be done in MS Word. If DOCX is your format of choice, we have you covered: our HTML to DOCX API will quicky & easily create a DOCX from the HTML encoding, allowing you to share and store your HTML within the MS Office ecosystem. You can take advantage of this API for free using the Java code examples below; you’ll just need to first register a free account on our website to receive your secure API key (this free-tier key comes with a limit of 800 API calls per month & zero additional commitments; perfect for small-scale projects & getting your apps off the ground).

Before we call the API function, we first need to install the API client. Let’s start by including a reference in the pom.xml repository:

<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>

And then we can add a reference to the pom.xml dependency:

<dependencies>
<dependency>
<groupId>com.github.Cloudmersive</groupId>
<artifactId>Cloudmersive.APIClient.Java</artifactId>
<version>v4.25</version>
</dependency>
</dependencies>

With installation complete, we can turn our attention to the controller & add the following imports:

// 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.ConvertWebApi;

Now we can begin to structure our API call. We need to structure a JSON input HTML string parameter like so:

{
"Html": "string"
}

And we can include that + our API key within the below code examples:

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");
ConvertWebApi apiInstance = new ConvertWebApi();
HtmlToOfficeRequest inputRequest = new HtmlToOfficeRequest(); // HtmlToOfficeRequest | HTML input to convert to DOCX
try {
byte[] result = apiInstance.convertWebHtmlToDocx(inputRequest);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ConvertWebApi#convertWebHtmlToDocx");
e.printStackTrace();
}

After that, we’re all set — no more code required. Easy as can be!

--

--

Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.