How to Compress PDF Files with JavaScript in NodeJS

Learn how to compress PDF files programmatically with JavaScript using the Compress PDF API Tool by pdfRest.
Share this page

Why Compress PDF with JavaScript?

Compressing PDF files is an essential task for optimizing storage space and improving download and upload times. The pdfRest Compress PDF API Tool provides a straightforward way to reduce PDF file sizes programmatically. This tutorial will demonstrate how to send an API call to Compress PDF using JavaScript.

For instance, if you're building a web application that allows users to upload reports, compressing these PDFs before storing them can save server space and make the reports quicker to access for users.

Compress PDF with JavaScript Code Example

// This request demonstrates how to reduce the file size of a PDF.
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('compression_level', 'medium');
data.append('output', 'pdfrest_compressed_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/compressed-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: GitHub

Breaking Down the JavaScript Code

The code provided demonstrates how to compress a PDF file using the pdfRest API in JavaScript:

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

This initializes the required modules: axios for making HTTP requests, FormData to construct the multipart form data, and fs to handle the file system.

var data = new FormData();
data.append('file', fs.createReadStream('/path/to/file'));
data.append('compression_level', 'medium');
data.append('output', 'pdfrest_compressed_pdf');

Here, a new FormData object is created and the PDF file along with compression parameters are appended to it. The 'compression_level' can be 'low', 'medium', or 'high', depending on the desired compression ratio.

var config = {
  // ... other configuration options
  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 request configuration, including the API endpoint URL, headers (with your API key), and the 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. The response is then logged to the console, or an error is logged if the request fails.

Beyond the Tutorial

By following the steps above, you've learned how to make an API call to compress a PDF file using JavaScript. This is a practical skill for any web application that handles PDFs, as it allows for efficient file management and faster data transfer. To explore the full capabilities of the pdfRest API, you can demo all of the pdfRest API Tools in the API Lab at API Lab and refer to the API Reference documentation at Cloud API Reference Guide.

Note: This is an example of a multipart API call. Code samples using JSON payloads can also be found at GitHub.

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