How to Add Images to PDF Files with JavaScript in NodeJS

Learn how to use JavaScript in NodeJS 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 JavaScript?

The pdfRest Add to PDF API Tool offers a powerful way to programmatically enhance PDF documents by adding images to them. This tutorial will guide you through the process of sending an API call to Add to PDF using JavaScript, a popular language for web development. By leveraging JavaScript alongside the pdfRest API, developers can seamlessly integrate PDF manipulation capabilities into their web applications or services.

Imagine you are developing a web application for event management. Users can upload their event brochures and add sponsor logos directly onto the brochure PDFs. Using the Add to PDF API, you can automate this process, allowing users to position logos on specific pages and at precise locations within their brochures, all without needing any manual PDF editing tools.

Add Images to PDF with JavaScript Code Example

/**
 * This request demonstrates how to apply an image to a PDF. Horizontal and vertical offsets of the image are measured in PDF units. (1 inch = 72 PDF units)
 */
var axios = require('axios');
var FormData = require('form-data');
var fs = require('fs');

// Create a new form data instance and append the PDF file and parameters to it
var data = new FormData();
data.append('file', fs.createReadStream('/path/to/file'));
data.append('image_file', fs.createReadStream('/path/to/file'));
data.append('x', '0');
data.append('y', '0');
data.append('page', '1');
data.append('output', 'pdfrest_pdf_with_added_image');

// define configuration options for axios request
var config = {
  method: 'post',
  maxBodyLength: Infinity, // set maximum length of the request body
  url: 'https://api.pdfrest.com/pdf-with-added-image', 
  headers: { 
    'Api-Key': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', // Replace with your API key
    ...data.getHeaders() // set headers for the request
  },
  data : data // set the data to be sent with the request
};

// send request and handle response or error
axios(config)
.then(function (response) {
  console.log(JSON.stringify(response.data));
})
.catch(function (error) {
  console.log(error); 
});

// If you would like to download the file instead of getting the JSON response, please see the 'get-resource-id-endpoint.js' sample.

Code provided is sourced from pdf-rest-api-samples on GitHub.

Breaking Down the Code

The code provided above demonstrates how to send a multipart request to the pdfRest API to add an image to a PDF document. Let's break down the key parts:

var axios = require('axios');
var FormData = require('form-data');
var fs = require('fs');

This initializes the required modules: axios for making HTTP requests, FormData for creating multipart/form-data payloads, and fs for file system operations.

var data = new FormData();
data.append('file', fs.createReadStream('/path/to/file'));
data.append('image_file', fs.createReadStream('/path/to/file'));
data.append('x', '0');
data.append('y', '0');
data.append('page', '1');
data.append('output', 'pdfrest_pdf_with_added_image');

Here, a new FormData object is created and populated with the PDF file, image file, and parameters such as the x and y offsets (measured in PDF units), the page number to add the image to, and the desired output filename.

var config = {
  method: 'post',
  maxBodyLength: Infinity,
  url: 'https://api.pdfrest.com/pdf-with-added-image', 
  headers: { 
    'Api-Key': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
    ...data.getHeaders()
  },
  data : data
};

The config object contains the settings for the axios request, including the API endpoint URL, the API key for authentication, and the form data payload.

axios(config)
.then(function (response) {
  console.log(JSON.stringify(response.data));
})
.catch(function (error) {
  console.log(error); 
});

The axios library is used to send the request and process the response. If successful, the response data is logged to the console; otherwise, the error is logged.

Beyond the Tutorial

In this tutorial, we've learned how to use JavaScript to make an API call to pdfRest's Add to PDF endpoint, allowing us to add an image to a PDF document. This capability can be integrated into various applications to automate and enhance document workflows.

Feel free to explore and demo all of the pdfRest API Tools in the API Lab. For further details on the API and its capabilities, 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 pdf-rest-api-samples.

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