How to Optimize PDF Files in Node.js

Cloudmersive
2 min readSep 29, 2023

--

To make PDFs containing large images more manageable for storage & for sharing across networks, file optimization is key.

Using the below code, we can take advantage of a free API that allows us to customize the quality of images in a PDF (from 0.0 to 1.0; low quality to high quality respectively). The default value for this operation is 0.3, which will ensure a greatly reduced file size while maintaining a reasonably high-quality result.

We can structure our API call in a few quick steps, beginning with SDK installation. We can install the SDK in one of two ways — either by running the following command:

npm install cloudmersive-convert-api-client --save

Or by adding the below snippet to our package.json:

  "dependencies": {
"cloudmersive-convert-api-client": "^2.6.3"
}

We can then copy the ready-to-run Node.js code examples below into our file. To authorize our requests for free, we can supply a free-tier API key (obtainable by registering a free account on the Cloudmersive website):

var CloudmersiveConvertApiClient = require('cloudmersive-convert-api-client');
var defaultClient = CloudmersiveConvertApiClient.ApiClient.instance;

// Configure API key authorization: Apikey
var Apikey = defaultClient.authentications['Apikey'];
Apikey.apiKey = 'YOUR API KEY';



var apiInstance = new CloudmersiveConvertApiClient.EditPdfApi();

var inputFile = Buffer.from(fs.readFileSync("C:\\temp\\inputfile").buffer); // File | Input file to perform the operation on.

var opts = {
'quality': 8.14 // Number | Quality level for the images in the PDF, ranging from 0.0 (low quality) to 1.0 (high quality); default is 0.3
};

var callback = function(error, data, response) {
if (error) {
console.error(error);
} else {
console.log('API called successfully. Returned data: ' + data);
}
};
apiInstance.editPdfReduceFileSize(inputFile, opts, callback);

The operation will be carried out in-memory, and the data from our operation will be released upon completion to ensure file security (the encoding for our optimized file will be returned in the API response).

--

--

Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.