Java PDF API — Getting Started

With Nutrient’s Java PDF API, you can quickly process your documents by making HTTP requests to one of our 50+ API tools. You can make a single request to one tool or combine API actions to generate, edit, OCR, and convert your document (1 document can have multiple API actions).

In this guide, we’ll go through how you can use Java to make HTTP requests with our API by:

  1. 1
    Installing the required dependencies
  2. 2
    Preparing the payload
  3. 3
    Making the request

You’ll use OkHttp to make HTTP requests, and you’ll use org.json to build the instructions JSON object.

Installing the Required Dependencies

You’ll need a Gradle-based Java project. The easiest way is to use IntelliJ and create one from there.

Screen capture of the IntelliJ new project wizard.

Now you can add your dependencies to the build.gradle file:

Groovy
dependencies {
    implementation 'com.squareup.okhttp3:okhttp:4.9.2'
    implementation 'org.json:json:20210307'
}

Finally, you’ll need to add document.pdf and logo.png files to the root of your Java project. You can use the sample files provided by us — document.pdf and logo.png — or use your own.

Your project is now ready to make requests to Nutrient DWS API. Next, you’ll add your main entry point to the app. Create a new PdpdfkitApiExample class and add a main method. You can also add all the imports you’re going to use:

Java
import okhttp3.*;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

public class PspdfkitApiExample {

    public static void main(String[] args) throws IOException {
      // Implement your call to Nutrient DWS API here.
    }
}

Make sure you set this class as your app’s entry point. At this point, you should be able to run this class directly from IntelliJ.

Next, you’ll implement your main method. For this guide, you’ll watermark a PDF. First, you need a new OkHttpClient:

Java
final OkHttpClient client = new OkHttpClient()
        .newBuilder()
        .build();

Next, you’ll prepare the payload.

Preparing the Payload

For this example, you don’t need any special configuration to create your instructions JSON object:

Java
final JSONObject instructions = new JSONObject()
  .put("parts", new JSONArray()
    .put(new JSONObject()
      .put("file", "document")
    )
  )
  .put("actions", new JSONArray()
    .put(new JSONObject()
      .put("type", "watermark")
      .put("image", "company-logo")
      .put("width", "50%")
    )
    .put(new JSONObject()
      .put("type", "watermark")
      .put("text", "Property of Nutrient")
      .put("width", 150)
      .put("height", 20)
      .put("left", 0)
      .put("bottom", "100%")
    )
  );

Here, you just build a JSON object using the org.json dependency you added earlier. For more details on the available options specifically related to watermarking, refer to our watermarking guide.

Next, you can create your RequestBody:

Java
final RequestBody body = new MultipartBody.Builder()
  .setType(MultipartBody.FORM)
  .addFormDataPart(
    "document",
    "document.pdf",
    RequestBody.create(
      new File("document.pdf"),
      MediaType.parse("application/pdf")
    )
  )
  .addFormDataPart(
    "company-logo",
    "logo.png",
    RequestBody.create(
      new File("logo.png"),
      MediaType.parse("image/png")
    )
  )
  .addFormDataPart("instructions", instructions.toString())
  .build();

Here, you assemble your multipart/form-data body containing the JSON instructions, your document.pdf that will be watermarked, and the logo.png that you’ll use as a watermark.

Making the Request

Finally, all that’s left is to actually make the request. Make sure to replace the your_api_key_here placeholder with your actual API key if it hasn’t yet been replaced:

Java
final Request request = new Request.Builder()
  .url("https://api.nutrient.io/build")
  .method("POST", body)
  .addHeader("Authorization", "Bearer your_api_key_here")
  .build();

final Response response = client.newCall(request).execute();

if (response.isSuccessful()) {
  Files.copy(
    response.body().byteStream(),
    FileSystems.getDefault().getPath("result.pdf"),
    StandardCopyOption.REPLACE_EXISTING
  );
} else {
  // Handle the error.
  throw new IOException(response.body().string());
}

This will actually send your request to Nutrient DWS API and save the resulting PDF in the root folder as result.pdf.

At this point, you should be able to directly run this from IntelliJ and see result.pdf appear in your root folder. And that’s it — you now have everything set up to use Nutrient DWS API from Java.

While this example made use of our watermarking API, this same approach can be used for all our available tools.

Full Code

For your convenience, here’s the whole class. Just copy it and run it:

Java
import okhttp3.*;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

public class PspdfkitApiExample {

  public static void main(String[] args) throws IOException {
    final OkHttpClient client = new OkHttpClient()
      .newBuilder()
      .build();

    final JSONObject instructions = new JSONObject()
      .put("parts", new JSONArray()
        .put(new JSONObject()
          .put("file", "document")
        )
      )
      .put("actions", new JSONArray()
        .put(new JSONObject()
          .put("type", "watermark")
          .put("image", "company-logo")
          .put("width", "50%")
        )
        .put(new JSONObject()
          .put("type", "watermark")
          .put("text", "Property of Nutrient")
          .put("width", 150)
          .put("height", 20)
          .put("left", 0)
          .put("bottom", "100%")
        )
      );

    final RequestBody body = new MultipartBody.Builder()
      .setType(MultipartBody.FORM)
      .addFormDataPart(
        "document",
        "document.pdf",
        RequestBody.create(
          new File("document.pdf"),
          MediaType.parse("application/pdf")
        )
      )
      .addFormDataPart(
        "company-logo",
        "logo.png",
        RequestBody.create(
          new File("logo.png"),
          MediaType.parse("image/png")
        )
      )
      .addFormDataPart("instructions", instructions.toString())
      .build();

    final Request request = new Request.Builder()
      .url("https://api.nutrient.io/build")
      .method("POST", body)
      .addHeader("Authorization", "Bearer your_api_key_here")
      .build();

    final Response response = client.newCall(request).execute();

    if (response.isSuccessful()) {
      Files.copy(
        response.body().byteStream(),
        FileSystems.getDefault().getPath("result.pdf"),
        StandardCopyOption.REPLACE_EXISTING
      );
    } else {
      // Handle the error.
      throw new IOException(response.body().string());
    }
  }
}