DEV Community

Cover image for How to reduce the file size of a PDF using Node.js
Samuel Durante for Woovi

Posted on

How to reduce the file size of a PDF using Node.js

At Woovi, we allow our customers to upload their documents with arbitrary sizes without requiring them to reduce the file size on their side.

Therefore, when opening accounts, we need to perform this reduction on these documents. For this purpose, we have created an automated solution using Ghostscript with Node.js to handle the compression.

import { existsSync } from 'fs';
import fs from 'fs/promises';
import path from 'path';
import { promisify } from 'util';

const execPromise = promisify(exec);

const cwd = process.cwd();

const compressPdf = async (base64: string): Promise<string> => {
  try {
    const tempFolder = path.join(cwd, "temp");
    const hasTempFolder = existsSync(tempFolder);

    if (!hasTempFolder) {
      await fs.mkdir(tempFolder);
    }

    const originalFilePath = path.join(cwd, "temp", "original.pdf");
    const compressFilePath = path.join(cwd, "temp", "compress.pdf");

    await fs.writeFile(originalFilePath, base64, "base64");

    await execPromise(
      `gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/ebook -dNOPAUSE -dQUIET -dBATCH -sOutputFile="${compressFilePath}" ${originalFilePath}`
    );

    const compressFileBase64 = await fs.readFile(compressFilePath, "base64");

    await fs.unlink(originalFilePath);
    await fs.unlink(compressFilePath);

    return compressFileBase64;
  } catch (error) {
    throw error;
  }
};
Enter fullscreen mode Exit fullscreen mode

The above function creates a temporary folder to store the processed files and performs compression using Ghostscript parameters. The original file is saved in this temporary folder, and Ghostscript is used to generate a compressed version of the file. Then, the compressed file is read and converted into a base64 string.


Woovi is a Startup that enables shoppers to pay as they like. To make this possible, Woovi provides instant payment solutions for merchants to accept orders.

If you want to work with us, we are hiring!


Photo by Dan Dennis on Unsplash

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.