How to Add Vector Lines and Rectangles to PDF Files with Java

Learn how to add vector shapes to PDF documents with Java using the pdfRest Add to PDF API Tool.
Share this page

Why Add Vector Lines and Rectangles to PDF Files with Java?

The pdfRest Add to PDF API Tool is a powerful resource for developers looking to programmatically add shapes, annotations, or other elements to PDF documents. By using this tool, you can enhance PDFs with custom graphics, making them more interactive and visually appealing. This tutorial will guide you through the process of sending an API call to the Add to PDF endpoint using Java, demonstrating how to integrate this functionality into your applications.

In a real-world scenario, imagine a publishing company that needs to add review panels and divider lines to PDF documents before they are finalized. By using the Add to PDF API, they can automate this process, ensuring consistency and saving time. This capability is particularly useful for businesses that regularly handle large volumes of documents and require a streamlined workflow for document enhancement.

Add Vector Lines and Rectangles to PDF Files 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.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.json.JSONArray;
import org.json.JSONObject;

public class PDFWithAddedShapes {

  // By default, we use the US-based API service. This is the primary endpoint for global use.
  private static final String API_URL = "https://api.pdfrest.com";

  // For GDPR compliance and enhanced performance for European users, you can switch to the EU-based
  // service by commenting out the URL above and uncommenting the URL below.
  // For more information visit https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work
  // private static final String API_URL = "https://eu-api.pdfrest.com";

  private static final String DEFAULT_FILE_PATH = "/path/to/input.pdf";
  private static final String DEFAULT_API_KEY = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";

  public static void main(String[] args) {
    File inputFile = new File(args.length > 0 ? args[0] : DEFAULT_FILE_PATH);
    Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load();

    // Add a lightly shaded review panel and a divider line to page one.
    // Coordinates are measured from the lower-left corner in PDF units (72 units = 1 inch).
    JSONArray shapes =
        new JSONArray()
            .put(
                new JSONObject()
                    .put("type", "rectangle")
                    .put("page", 1)
                    .put("x", 54)
                    .put("y", 540)
                    .put("width", 504)
                    .put("height", 108)
                    .put("fill_color_rgb", "245,247,250")
                    .put("stroke_color_rgb", "26,72,112")
                    .put("stroke_width", 1)
                    .put("tag_is_artifact", true))
            .put(
                new JSONObject()
                    .put("type", "line")
                    .put("page", 1)
                    .put("x1", 72)
                    .put("y1", 576)
                    .put("x2", 540)
                    .put("y2", 576)
                    .put("stroke_color_rgb", "26,72,112")
                    .put("stroke_width", 1.5)
                    .put("tag_actual_text", "Review section divider")
                    .put("tag_structure_type", "Figure"));

    RequestBody fileBody = RequestBody.create(inputFile, MediaType.parse("application/pdf"));
    RequestBody requestBody =
        new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("file", inputFile.getName(), fileBody)
            .addFormDataPart("shape_objects", shapes.toString())
            .addFormDataPart("tag_enabled", "true")
            .addFormDataPart("output", "review-panel")
            .build();
    Request request =
        new Request.Builder()
            .header("Accept", "application/json")
            .header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY))
            .url(API_URL + "/pdf-with-added-shapes")
            .post(requestBody)
            .build();

    OkHttpClient client = new OkHttpClient.Builder().readTimeout(60, TimeUnit.SECONDS).build();
    try (Response response = client.newCall(request).execute()) {
      System.out.println("Response status code: " + response.code());
      if (response.body() != null) {
        System.out.println(new JSONObject(response.body().string()).toString(2));
      }
    } catch (IOException error) {
      throw new RuntimeException(error);
    }
  }
}

Source: GitHub

Breaking Down the Code

The code begins by importing necessary libraries and defining constants. The API_URL is set to the US-based endpoint by default, but an EU-based endpoint is available for GDPR compliance. The DEFAULT_FILE_PATH and DEFAULT_API_KEY are placeholders for the PDF file path and API key, respectively.

File inputFile = new File(args.length > 0 ? args[0] : DEFAULT_FILE_PATH);
Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load();

Here, the code checks if a file path is provided as an argument; otherwise, it uses the default path. The Dotenv library loads environment variables, which can include sensitive information like the API key.

JSONArray shapes = new JSONArray()
    .put(new JSONObject()
        .put("type", "rectangle")
        .put("page", 1)
        .put("x", 54)
        .put("y", 540)
        .put("width", 504)
        .put("height", 108)
        .put("fill_color_rgb", "245,247,250")
        .put("stroke_color_rgb", "26,72,112")
        .put("stroke_width", 1)
        .put("tag_is_artifact", true))
    .put(new JSONObject()
        .put("type", "line")
        .put("page", 1)
        .put("x1", 72)
        .put("y1", 576)
        .put("x2", 540)
        .put("y2", 576)
        .put("stroke_color_rgb", "26,72,112")
        .put("stroke_width", 1.5)
        .put("tag_actual_text", "Review section divider")
        .put("tag_structure_type", "Figure"));

This snippet creates a JSON array of shapes to be added to the PDF. The shapes include a rectangle and a line, each with specific properties such as type, page, coordinates, color, and stroke width. These properties define how and where the shapes will appear on the PDF.

RequestBody fileBody = RequestBody.create(inputFile, MediaType.parse("application/pdf"));
RequestBody requestBody = new MultipartBody.Builder()
    .setType(MultipartBody.FORM)
    .addFormDataPart("file", inputFile.getName(), fileBody)
    .addFormDataPart("shape_objects", shapes.toString())
    .addFormDataPart("tag_enabled", "true")
    .addFormDataPart("output", "review-panel")
    .build();

This part constructs the multipart request body. It includes the PDF file, the shapes JSON array, and additional parameters like tag_enabled and output. The tag_enabled parameter, when set to true, ensures that tags are applied to the shapes, while output specifies the desired output format.

Request request = new Request.Builder()
    .header("Accept", "application/json")
    .header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY))
    .url(API_URL + "/pdf-with-added-shapes")
    .post(requestBody)
    .build();

A request object is created with headers for content type and API key, and it specifies the endpoint URL. The POST method is used to send the request with the constructed request body.

OkHttpClient client = new OkHttpClient.Builder().readTimeout(60, TimeUnit.SECONDS).build();
try (Response response = client.newCall(request).execute()) {
  System.out.println("Response status code: " + response.code());
  if (response.body() != null) {
    System.out.println(new JSONObject(response.body().string()).toString(2));
  }
} catch (IOException error) {
  throw new RuntimeException(error);
}

The OkHttpClient is configured to handle the request, with a read timeout of 60 seconds. The response is then processed, printing the status code and response body if available.

Beyond the Tutorial

In this tutorial, you learned how to use Java to make an API call to pdfRest's Add to PDF endpoint, allowing you to add custom shapes to a PDF document. This example demonstrated the use of a multipart API call, which is useful for handling file uploads and complex data structures.

To further explore the capabilities of pdfRest, you can demo all of the API Tools in the API Lab. For more detailed information, refer to the API Reference Guide. Note that this tutorial is an example of a multipart API call, and code samples using JSON payloads can be found on GitHub.

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