How to Add Images to PDF Files with Java

Learn how to use Java to add an image to a PDF by calling Add to PDF API Tool by pdfRest.
Share this page

Why Add Images to PDF with Java?

The pdfRest Add to PDF API Tool provides a convenient way to programmatically add images to PDF documents. By using this API, developers can automate the process of manipulating PDF files, which can be particularly useful when dealing with large volumes of documents or when customizing documents on-the-fly.

This tutorial will guide you through the process of sending an API call to Add to PDF using Java, showcasing how to integrate this functionality into Java applications.

Consider a real-world scenario where a company needs to add their logo to a batch of invoices generated as PDFs, or a user wants to embed scanned signatures into contracts. The Add to PDF API tool simplifies these tasks by allowing users to programmatically insert images into specific locations within a PDF, saving time and reducing the risk of manual errors.

Add Images to 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 PDFWithAddedImage {

  // Specify the path to your file here, or as the first argument when running the program.
  private static final String DEFAULT_FILE_PATH = "/path/to/file.pdf";

  // Specify the path to your image file here, or as the second argument when running the
  // program.
  private static final String DEFAULT_IMAGE_PATH = "/path/to/file.xml";

  // 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, imageFile;
    if (args.length > 1) {
      inputFile = new File(args[0]);
      imageFile = new File(args[1]);
    } else {
      inputFile = new File(DEFAULT_FILE_PATH);
      imageFile = new File(DEFAULT_IMAGE_PATH);
    }

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

    final RequestBody inputFileRequestBody =
        RequestBody.create(inputFile, MediaType.parse("application/pdf"));
    final RequestBody imageFileRequestBody =
        RequestBody.create(imageFile, MediaType.parse("application/png"));
    RequestBody requestBody =
        new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("file", inputFile.getName(), inputFileRequestBody)
            .addFormDataPart("image_file", imageFile.getName(), imageFileRequestBody)
            .addFormDataPart("page", "1")
            .addFormDataPart("x", "0")
            .addFormDataPart("y", "0")
            .build();
    Request request =
        new Request.Builder()
            .header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY))
            .url("https://api.pdfrest.com/pdf-with-added-image")
            .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);
  }
}

Code source: GitHub

Breaking Down the Code

The Java code provided above demonstrates how to make a multipart API call to the pdfRest Add to PDF endpoint. Let's break down the key components:

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

This line initializes the Dotenv library to load the API key from a .env file or an environment variable. It gracefully handles missing or malformed .env files.

RequestBody requestBody = new MultipartBody.Builder()
  .setType(MultipartBody.FORM)
  .addFormDataPart("file", inputFile.getName(), inputFileRequestBody)
  .addFormDataPart("image_file", imageFile.getName(), imageFileRequestBody)
  .addFormDataPart("page", "1")
  .addFormDataPart("x", "0")
  .addFormDataPart("y", "0")
  .build();

This snippet constructs the multipart request body. It includes the PDF file, the image file, and the parameters specifying the page number and the (x, y) coordinates where the image will be placed on the PDF.

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

This creates the HTTP request with the necessary headers, including the API key, and specifies the POST method with the previously built request body.

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

This line sends the HTTP request to the pdfRest API and captures the response. The response code and body are then printed out, with the body being formatted as pretty JSON.

Beyond the Tutorial

In this tutorial, you've learned how to use Java to make an API call to pdfRest's Add to PDF endpoint to add an image to a PDF document. By understanding how to construct and send a multipart request, you can now integrate this functionality into your own Java applications for various document processing tasks.

To explore and demo all of the pdfRest API Tools, visit the API Lab. For more detailed information, 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.