How to Split PDF with JavaScript in NodeJS

Share this page

Why Split a PDF Apart and How?

The pdfRest Split PDF API Tool is a powerful resource for programmatically splitting a single PDF document into multiple separate files. This feature can be particularly useful in scenarios where you need to extract specific pages or sections from a large PDF, such as when you want to distribute individual chapters of a book or separate documents from a batch of scanned pages.

In this tutorial, we will demonstrate how to send an API call to the Split PDF endpoint using JavaScript.

JavaScript Code Example

/**
 * This request demonstrates how to split a PDF document into three files by specifying the pages that will be included in each.
 * pages[] is an optional parameter that accepts page numbers and/or ranges separated by commas. In addition, pages[] supports several keywords: even, odd, and last.
 */
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[]', 'even');
data.append('pages[]', 'odd');
data.append('pages[]', '1,3,4-6');
data.append('output', 'pdfrest_split_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/split-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 code reference: pdf-rest-api-samples repository

Breaking Down the JavaScript

The code snippet provided is a complete example of how to use the pdfRest Split PDF API with JavaScript. Let's break down each part of the code:

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

This section imports the required modules. axios is used for making HTTP requests, FormData is used for building form data payloads, and fs is for file system operations.

var data = new FormData();
data.append('file', fs.createReadStream('/path/to/file'));
data.append('pages[]', 'even');
data.append('pages[]', 'odd');
data.append('pages[]', '1,3,4-6');
data.append('output', 'pdfrest_split_pdf');

Here, we create a new FormData instance and append the PDF file and parameters. The 'file' field should contain the file stream of the PDF you want to split. The 'pages[]' parameter is optional and allows you to specify which pages to include in each split document, supporting page numbers, ranges, and keywords like 'even', 'odd', and 'last'. The 'output' field is used to specify the base name for the output files.

var config = {
  // ...
  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
};

The config object contains the configuration for the axios request. The 'Api-Key' header must be replaced with your actual API key from pdfRest. The data.getHeaders() method is used to correctly set multipart/form-data headers.

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 with the specified config. Upon success, the response data is logged to the console. In case of an error, the error is logged.

Beyond the Tutorial with pdfRest

In this tutorial, we walked through the process of making an API call to the pdfRest Split PDF endpoint using JavaScript. By following the steps outlined, you can split a PDF document into separate files based on specific pages or criteria. To explore more capabilities and demo all of the pdfRest API Tools, visit the API Lab. For further information and documentation, refer to the Cloud 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 repository.

Generate a self-service API Key now!

Create your FREE API Key to start processing PDFs in seconds, only possible with pdfRest.

Compare Plans
Contact Us