Tutorials

How to Convert DOCX to PDF Using Java - Free PDF Converter API

By ComPDFKit | Tue. 23 Jan. 2024
PDF APIConversionJava

Consider converting your Word document to PDF before you send it to anyone else. This will ensure that the document will look the same on a variety of devices and that it can be viewed by recipients who do not have MS Word installed. In this post, you’ll learn how to convert Word Doc or Docx to PDF in your Java application using ComPDFKit’s Word to PDF API. With our API, you can convert up to 1000 PDF files per month for free. All you need to do is create a free account to get access to your API key.

 

ComPDFKit API

 

Document conversion is just one of our 30+ PDF API tools. You can combine our conversion tool with other tools to create complex document processing workflows. You’ll be able to convert various file formats from or to PDFs, and also to:

 

- Merge, split, insert, extract, delete specific PDF pages

 

- OCR, watermark, or compress PDFs

 

- Compare documents (including content comparison and overlay comparison)

 

 

Request Workflow

 

The processing workflow of the ComPDFKit API is very simple. It consists of four basic request instructions: create a task, upload a file, execute a task, and download a result file. Through these four requests, you can select the corresponding PDF tool to process your file and obtain the download link of the result file.

 

ComPDFKit API request workflow

 

 

How to Convert DOCX to PDF Using Java

 

The steps to access the Word to PDF API tool and process PDF conversion are as below: 

 

Step 1 — Creating a Free Account on ComPDFKit

 

Go to our website, where you’ll see the page below, prompting you to create your free account.

 

sign up ComPDFKit API

 

Once you’ve created your account, you’ll be welcomed by the page below, which shows an overview of your plan details.

 

Dashboard of ComPDFKit API

 

As you can see on the dashboard, you can process 1000 documents per month for free, and you’ll be able to access all our PDF API tools.

 

Step 2 — Obtaining the API Key for Authentication

 

After you’ve verified your email, you can get your API key from the dashboard. In the menu on the left, click API Keys. You’ll see the following page, which is an overview of your keys:

 

 

Get API Key for authentication

 

Now You need to replace public_key and secret_key with accessToken in the publicKey and secretKey authentication return values you get from the console.

 

import java.io.*;
 import okhttp3.*;
 public class main {
   public static void main(String []args) throws IOException{
     OkHttpClient client = new OkHttpClient().newBuilder()
       .build();
     MediaType mediaType = MediaType.parse("text/plain");
     RequestBody body = RequestBody.create(mediaType, "{\n    \"publicKey\": \"{{public_key}}\",\n    \"secretKey\": \"{{secret_key}}\"\n}");
     Request request = new Request.Builder()
       .url("https://api-server.compdf.com/server/v1/oauth/token")
       .method("POST", body)
       .build();
     Response response = client.newCall(request).execute();
   }
 }

 

Step 3 — Creating Task 

 

You need to replace the accessToken which was obtained from the previous step, and replace the language type you want to display the error information. After replacing them, you will get the taskId in the response data.

 

import java.io.*;
 import okhttp3.*;
 public class main {
   public static void main(String []args) throws IOException{
     OkHttpClient client = new OkHttpClient().newBuilder()
       .build();
     MediaType mediaType = MediaType.parse("text/plain");
     RequestBody body = RequestBody.create(mediaType, "");
     Request request = new Request.Builder()
       .url("https://api-server.compdf.com/server/v1/task/docx/pdf?language={{language}}")
       .method("GET", body)
       .addHeader("Authorization", "Bearer {{accessToken}}")
       .build();
     Response response = client.newCall(request).execute();
   }
 }

 

Step 4 — Uploading Files

 

Replace the file you want to convert, the taskId obtained in the previous step, the language type you want to display the error information, and the accessToken obtained in the first step.

 

import java.io.*;
 import okhttp3.*;
 public class main {
   public static void main(String []args) throws IOException{
     OkHttpClient client = new OkHttpClient().newBuilder()
       .build();
     MediaType mediaType = MediaType.parse("text/plain");
     RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
       .addFormDataPart("file","{{file}}",
                        RequestBody.create(MediaType.parse("application/octet-stream"),
                                           new File("")))
       .addFormDataPart("taskId","{{taskId}}")
       .addFormDataPart("language","{{language}}")
       .addFormDataPart("password","")
       .build();
     Request request = new Request.Builder()
       .url("https://api-server.compdf.com/server/v1/file/upload")
       .method("POST", body)
       .addHeader("Authorization", "Bearer {{accessToken}}")
       .build();
     Response response = client.newCall(request).execute();
   }
 }

 

Step 5 — Processing Files

 

Replace the taskId you obtained from the Create task, and the accessToken obtained in the first step, and replace the language type you want to display the error information.

 

import java.io.*;
 import okhttp3.*;
 public class main {
  public static void main(String []args) throws IOException{
    OkHttpClient client = new OkHttpClient().newBuilder()
      .build();
    MediaType mediaType = MediaType.parse("text/plain");
    RequestBody body = RequestBody.create(mediaType, "");
    Request request = new Request.Builder()
      .url("https://api-server.compdf.com/server/v1/execute/start?taskId={{taskId}}&language={{language}}")
      .method("GET", body)
      .addHeader("Authorization", "Bearer {{accessToken}}")
      .build();
    Response response = client.newCall(request).execute();
  }
 }

 

Step 6 — Getting Task Information

 

Replace taskId with the taskId you obtained from the step "Create the task", access_token replaced by access_token obtained in the first step.

 

import java.io.*;
 import okhttp3.*;
 public class main {
   public static void main(String []args) throws IOException{
     OkHttpClient client = new OkHttpClient().newBuilder()
       .build();
     MediaType mediaType = MediaType.parse("text/plain");
     RequestBody body = RequestBody.create(mediaType, "");
     Request request = new Request.Builder()
       .url("https://api-server.compdf.com/server/v1/task/taskInfo?taskId={{taskId}}")
       .method("GET", body)
       .addHeader("Authorization", "Bearer {{accessToken}}")
       .build();
     Response response = client.newCall(request).execute();
   }
 }

 

Conclusion

 

In this post, you learned how to easily and seamlessly convert DOCX files to PDF files for your application using our Word to PDF API by Java. Besides, you can also get started with ComPDFKit API library in Java with only one step. You can integrate all these PDF functionalities into your applications or systems. With the same API token, you can also perform other operations, such as splitting or merging PDFs, adding watermarks, using OCR and AI table recognition, and more. To get started with a free trial, sign up here.