How to Merge PDF Files with JavaScript in NodeJS

Share this page

Why Use Merge PDFs with JavaScript?

The pdfRest Merge PDFs API Tool allows users to combine multiple PDF files into a single document. This can be incredibly useful in various scenarios, such as consolidating reports, combining scanned documents, or merging chapters of a book.

In this tutorial, we will demonstrate how to send an API call to the Merge PDFs tool using JavaScript.

JavaScript Code Sample

// This request demonstrates how to merge multiple PDFs into a single document.
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('pages[]', '1-last');
data.append('type[]', 'file');
data.append('file', fs.createReadStream('/path/to/file'));
data.append('pages[]', '1-last');
data.append('type[]', 'file');
data.append('output', 'pdfrest_merged_pdf');

// define configuration options for axios request
var config = {
  method: 'post',
  maxBodyLength: Infinity, // set maximum length of the request body
  url: 'https://api.pdfrest.com/merged-pdf', 
  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.

Source: pdf-rest-api-samples

Breaking Down the JavaScript Code

The NodeJS example uses axios for the request, form-data to assemble repeated multipart fields, and fs to stream each local PDF. Install the external packages with npm install axios form-data if they are not already part of the project.

var data = new FormData();
data.append('file', fs.createReadStream('/path/to/first.pdf'));
data.append('pages[]', '1-last');
data.append('type[]', 'file');
data.append('file', fs.createReadStream('/path/to/second.pdf'));
data.append('pages[]', '1-last');
data.append('type[]', 'file');

The repeated fields are positional. Every file or id[] input needs one corresponding pages[] value and one type[] value in the same merge order. Here, type[] is file for both uploads, and 1-last includes every page from each document.

Page expressions also support comma-separated pages and ranges, reversed ranges, even, and odd. To reuse a previously uploaded PDF, submit its id[] with a matching type[] value of id. A multipart request may mix uploaded files and resource IDs as long as all corresponding fields preserve the same order.

data.append('output', 'pdfrest_merged_pdf');

output sets the merged filename without the .pdf extension. If omitted, the service applies its default output name.

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

data.getHeaders() provides the multipart boundary. maxBodyLength: Infinity prevents Axios from applying its own finite request-body limit before the service receives the PDFs.

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

The response identifies the newly merged PDF resource. In production, inspect error.response for API validation details, especially when the number or order of file, id[], pages[], and type[] values do not correspond.

Next Steps with pdfRest

We've covered how to use JavaScript to call the pdfRest Merge PDFs API. This allows you to programmatically merge multiple PDF files into a single document. You can now experiment with all of the pdfRest API Tools in the API Lab, and refer to the API Reference documentation for more details.

Note: This is an example of a multipart API call. Code samples using JSON payloads can be found at https://github.com/pdfrest/pdfrest-api-samples/blob/main/JavaScript/Endpoint%20Examples/JSON%20Payload/merged-pdf.js.

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