How to Add Vector Lines and Rectangles to PDF Files with JavaScript in NodeJS

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

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

The pdfRest Add to PDF API Tool is a powerful utility that allows developers to programmatically add shapes and annotations to PDF documents using JavaScript. This tutorial will guide you through the process of sending an API call to the Add to PDF endpoint using JavaScript, enabling you to enhance PDF documents with custom shapes and designs.

In real-world scenarios, a user might use the Add to PDF functionality to enhance reports or documents with visual elements such as dividers, highlights, or annotations. For example, a company could use this tool to automatically add branding elements or review sections to PDF reports generated from their data analytics platform.

Add Vector Lines and Rectangles to PDF Files with JavaScript Code Example

/**
 * Add a review-panel background and divider line to a PDF.
 * PDF coordinates begin at the lower-left corner; 72 PDF units equal one inch.
 */
const axios = require("axios");
const FormData = require("form-data");
const fs = require("fs");

// By default, we use the US-based API service. This is the primary endpoint for global use.
const apiUrl = "https://api.pdfrest.com";

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

const shapes = [
  {
    type: "rectangle",
    page: 1,
    x: 54,
    y: 540,
    width: 504,
    height: 108,
    fill_color_rgb: "245,247,250",
    stroke_color_rgb: "26,72,112",
    stroke_width: 1,
    tag_is_artifact: true,
  },
  {
    type: "line",
    page: 1,
    x1: 72,
    y1: 576,
    x2: 540,
    y2: 576,
    stroke_color_rgb: "26,72,112",
    stroke_width: 1.5,
    tag_actual_text: "Review section divider",
    tag_structure_type: "Figure",
  },
];

const form = new FormData();
form.append("file", fs.createReadStream("/path/to/input.pdf"));
form.append("shape_objects", JSON.stringify(shapes));
form.append("tag_enabled", "true");
form.append("output", "review-panel");

axios({
  method: "post",
  maxBodyLength: Infinity,
  url: `${apiUrl}/pdf-with-added-shapes`,
  headers: {
    "Api-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", // Replace with your API key.
    ...form.getHeaders(),
  },
  data: form,
})
  .then((response) => console.log(JSON.stringify(response.data, null, 2)))
  .catch((error) => console.log(error.response?.data || error.message));

// To download the returned file, use the outputId with the get-resource-id endpoint sample.

Source: GitHub Repository

Breaking Down the Code

The code begins by importing necessary modules: axios for making HTTP requests, form-data for handling form submissions, and fs for file system operations.

const apiUrl = "https://api.pdfrest.com";

This line sets the API endpoint URL. For European users concerned with GDPR compliance, a separate EU endpoint is available.

const shapes = [
  {
    type: "rectangle",
    page: 1,
    x: 54,
    y: 540,
    width: 504,
    height: 108,
    fill_color_rgb: "245,247,250",
    stroke_color_rgb: "26,72,112",
    stroke_width: 1,
    tag_is_artifact: true,
  },
  {
    type: "line",
    page: 1,
    x1: 72,
    y1: 576,
    x2: 540,
    y2: 576,
    stroke_color_rgb: "26,72,112",
    stroke_width: 1.5,
    tag_actual_text: "Review section divider",
    tag_structure_type: "Figure",
  },
];

This array defines the shapes to be added to the PDF. Each shape object includes properties such as type, position, dimensions, and styling attributes. The tag_is_artifact and tag_actual_text fields are used for accessibility tagging.

form.append("file", fs.createReadStream("/path/to/input.pdf"));
form.append("shape_objects", JSON.stringify(shapes));
form.append("tag_enabled", "true");
form.append("output", "review-panel");

These lines append the PDF file, shape definitions, and additional parameters to the form data. The tag_enabled parameter enables tagging for accessibility, and output specifies the output file name.

axios({
  method: "post",
  maxBodyLength: Infinity,
  url: `${apiUrl}/pdf-with-added-shapes`,
  headers: {
    "Api-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", // Replace with your API key.
    ...form.getHeaders(),
  },
  data: form,
})

This snippet sends a POST request to the API endpoint, including the form data and headers. The Api-Key must be replaced with your actual API key.

Beyond the Tutorial

In this tutorial, you learned how to use JavaScript to call the pdfRest Add to PDF API and add custom shapes to a PDF document. This example demonstrates how to enhance PDF files with visual elements programmatically.

To explore further, you can demo all of the pdfRest API Tools in 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 Repository.

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