How to Digitally Sign PDF Files with Java

Learn how to apply digital signatures to PDF files with Java using pdfRest's Sign PDF API Tool.
Share this page

Why Digitally Sign PDFs with Java?

The pdfRest Sign PDF API Tool provides a convenient way to digitally sign PDF documents programmatically. This tutorial will guide you through the process of sending an API call to the Sign PDF endpoint using Java. By leveraging this tool, developers can automate the signing of PDF documents, ensuring authenticity and integrity.

A business might use the Sign PDF API to streamline its document signing process. For example, a company could automatically sign contracts, invoices, or other legal documents before sending them to clients. This not only saves time but also reduces the risk of human error in the signing process.

Sign PDF with Java Code Example

import io.github.cdimascio.dotenv.Dotenv;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.*;
import org.json.JSONObject;

public class SignedPDF {

  // Specify your API key here, or in the environment variable PDFREST_API_KEY.
  // You can also put the environment variable in a .env file.
  private static final String DEFAULT_API_KEY = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";

  public static void main(String[] args) {
    File inputFile, credentialFile, passphraseFile, logoFile;
    if (args.length > 3) {
      inputFile = new File(args[0]);
      credentialFile = new File(args[1]);
      passphraseFile = new File(args[2]);
      logoFile = new File(args[3]);
    } else {
      inputFile = new File("/path/to/input.pdf");
      credentialFile = new File("/path/to/credentials.pfx");
      passphraseFile = new File("/path/to/passphrase.txt");
      logoFile = new File("/path/to/logo.png");
    }

    final Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load();

    JSONObject bottomLeft = new JSONObject();
    bottomLeft.put("x", "0");
    bottomLeft.put("y", "0");

    JSONObject topRight = new JSONObject();
    topRight.put("x", "216");
    topRight.put("y", "72");

    JSONObject location = new JSONObject();
    location.put("bottom_left", bottomLeft);
    location.put("top_right", topRight);
    location.put("page", "1");

    JSONObject display = new JSONObject();
    display.put("include_distinguished_name", "true");
    display.put("include_datetime", "true");
    display.put("contact", "My contact information");
    display.put("location", "My signing location");
    display.put("name", "John Doe");
    display.put("reason", "My reason for signing");

    JSONObject signatureConfig = new JSONObject();
    signatureConfig.put("type", "new");
    signatureConfig.put("name", "esignature");
    signatureConfig.put("logo_opacity", "0.5");
    signatureConfig.put("location", location);
    signatureConfig.put("display", display);

    final RequestBody inputFileRequestBody =
        RequestBody.create(inputFile, MediaType.parse("application/pdf"));
    final RequestBody credentialFileRequestBody =
        RequestBody.create(credentialFile, MediaType.parse("application/x-pkcs12"));
    final RequestBody passphraseFileRequestBody =
        RequestBody.create(passphraseFile, MediaType.parse("text/plain"));
    final RequestBody logoFileRequestBody =
        RequestBody.create(logoFile, MediaType.parse("image/png"));
    RequestBody requestBody =
        new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("file", inputFile.getName(), inputFileRequestBody)
            .addFormDataPart(
                "pfx_credential_file", credentialFile.getName(), credentialFileRequestBody)
            .addFormDataPart(
                "pfx_passphrase_file", passphraseFile.getName(), passphraseFileRequestBody)
            .addFormDataPart("logo_file", logoFile.getName(), logoFileRequestBody)
            .addFormDataPart("signature_configuration", signatureConfig.toString())
            .addFormDataPart("output", "example_out.pdf")
            .build();
    Request request =
        new Request.Builder()
            .header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY))
            .url("https://api.pdfrest.com/signed-pdf")
            .post(requestBody)
            .build();
    try {
      OkHttpClient client =
          new OkHttpClient().newBuilder().readTimeout(60, TimeUnit.SECONDS).build();

      Response response = client.newCall(request).execute();
      System.out.println("Result code " + response.code());
      if (response.body() != null) {
        System.out.println(prettyJson(response.body().string()));
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  private static String prettyJson(String json) {
    // https://stackoverflow.com/a/9583835/11996393
    return new JSONObject(json).toString(4);
  }
}

Source: GitHub

Breaking Down the Code

The Java code begins by importing necessary libraries and setting up environment variables. The DEFAULT_API_KEY is defined for authentication purposes. The main method handles input files, which include the PDF to be signed, the credential file, the passphrase file, and a logo file.

File inputFile, credentialFile, passphraseFile, logoFile;
if (args.length > 3) {
  inputFile = new File(args[0]);
  credentialFile = new File(args[1]);
  passphraseFile = new File(args[2]);
  logoFile = new File(args[3]);
} else {
  inputFile = new File("/path/to/input.pdf");
  credentialFile = new File("/path/to/credentials.pfx");
  passphraseFile = new File("/path/to/passphrase.txt");
  logoFile = new File("/path/to/logo.png");
}

The Dotenv library is used to load environment variables, which include the API key.

final Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load();

Next, JSON objects are created to define the signature's location and display settings on the PDF.

JSONObject bottomLeft = new JSONObject();
bottomLeft.put("x", "0");
bottomLeft.put("y", "0");

JSONObject topRight = new JSONObject();
topRight.put("x", "216");
topRight.put("y", "72");

JSONObject location = new JSONObject();
location.put("bottom_left", bottomLeft);
location.put("top_right", topRight);
location.put("page", "1");

The RequestBody objects are created for each file, specifying the media type. These are then added to a MultipartBody for the API request.

RequestBody requestBody =
    new MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addFormDataPart("file", inputFile.getName(), inputFileRequestBody)
        .addFormDataPart(
            "pfx_credential_file", credentialFile.getName(), credentialFileRequestBody)
        .addFormDataPart(
            "pfx_passphrase_file", passphraseFile.getName(), passphraseFileRequestBody)
        .addFormDataPart("logo_file", logoFile.getName(), logoFileRequestBody)
        .addFormDataPart("signature_configuration", signatureConfig.toString())
        .addFormDataPart("output", "example_out.pdf")
        .build();

The Request object is configured with the API key and the URL for the Sign PDF endpoint. The OkHttpClient is used to execute the request, and the response is printed.

Request request =
    new Request.Builder()
        .header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY))
        .url("https://api.pdfrest.com/signed-pdf")
        .post(requestBody)
        .build();

Beyond the Tutorial

In this tutorial, you learned how to send an API request to the pdfRest Sign PDF endpoint using Java. This example demonstrates how to automate the signing of PDF documents, which can be a valuable tool in various business applications.

To explore more, try out all the pdfRest API Tools in the API Lab. For detailed documentation, refer to the API Reference Guide.

Note: This is an example of a multipart API call. Code samples using JSON payloads can be found at GitHub.

Generate a self-service API Key now!
Create your FREE API Key to start processing PDFs in seconds, only possible with pdfRest.