Getting Started with Java

PSPDFKit API is offered as a simple HTTP API, so using it from Java is as easy as making an HTTP request. The following will guide you through how to install the required dependencies, and it’ll show you how to make a request.

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

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 PSPDFKit 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 PSPDFKit 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 PSPDFKit")
      .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.pspdfkit.com/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 PSPDFKit 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 PSPDFKit 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 PSPDFKit")
          .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.pspdfkit.com/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());
    }
  }
}