← back to blog

Compress PDFs in Node.js: Ghostscript vs qpdf vs pdf-lib, measured

We ran Ghostscript, qpdf and pdf-lib on three kinds of PDF. The best choice depends on what's inside the file, and for text-heavy PDFs the lossless option won.

by Horizech Team8 min read

Most "compress a PDF in Node.js" answers say: shell out to Ghostscript with -dPDFSETTINGS=/ebook. That's a good default, but it isn't always the best choice. On two of our three test files it either did nothing or lost to a lossless tool that's twice as fast.

We measured Ghostscript, qpdf and pdf-lib on three common kinds of PDF and wrote down every number. The code is at the end.

Short answer: run a lossless qpdf pass and a Ghostscript /ebook pass, then keep whichever file is smaller. Never return a file larger than the input. That one rule got the best result on every file we tested.

The three test files

PDFs differ a lot in what makes them big, so we built one of each common kind:

FilePagesSizeWhat's inside
photos-lossless.pdf87,402 KBPhotos embedded as PNG (lossless), like many screenshot and scan-to-PDF exports
photos-jpeg.pdf81,270 KBThe same photos embedded as JPEG quality 95, like phone "scan document" apps
text-report.pdf1781,127 KBA long text manual exported from LibreOffice Writer

The photos are freely licensed sample images from the scikit-image sample data. The text is the Next.js "Getting started" docs, laid out by LibreOffice 24.2. The script that builds all three is in the example folder, so you can rerun everything with your own files.

What we compared

# Ghostscript 10.02.1: rewrites the whole PDF, recompresses images (lossy)
gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.6 -dPDFSETTINGS=/ebook \
   -dNOPAUSE -dBATCH -dQUIET -sOutputFile=out.pdf in.pdf

# qpdf 11.9.0: repacks objects into compressed object streams (lossless)
qpdf --object-streams=generate --compress-streams=y \
     --recompress-flate --compression-level=9 in.pdf out.pdf
// pdf-lib 1.17.1: pure JavaScript, no binaries (lossless)
const doc = await PDFDocument.load(await readFile('in.pdf'))
await writeFile('out.pdf', await doc.save({ useObjectStreams: true }))

For each output we recorded the size, the median time of 3 runs, and a quality check. We rendered page 1 at 100 dpi and compared it with the original render using PSNR. Higher is closer, "identical" means pixel-for-pixel the same, and above roughly 35 dB differences are hard to see at normal zoom. The machine was a 4 vCPU Linux container on Ubuntu 24.04 with Node 22.

Results

Photos embedded losslessly (7,402 KB):

MethodOutputSavedTimePage 1 quality
gs /screen252 KB97%331 ms35.4 dB
gs /ebook389 KB95%298 ms35.4 dB
gs /printer743 KB90%254 ms38.6 dB
qpdf (lossless)7,398 KB0%567 msidentical
pdf-lib (lossless)7,402 KB0%30 msidentical

Ghostscript wins by a mile here. It re-encodes the PNG photos as JPEG, which a lossless tool can't do.

Photos already embedded as JPEG (1,270 KB):

MethodOutputSavedTimePage 1 quality
gs /screen646 KB49%176 ms51.3 dB
gs /ebook1,274 KB0% (slightly bigger)102 ms51.3 dB
gs /printer1,277 KB-1% (bigger)112 ms51.3 dB
qpdf (lossless)1,270 KB0%13 msidentical
pdf-lib (lossless)1,270 KB0%17 msidentical

This is the case that catches people out. /ebook and /printer made the file bigger. Only /screen helped, because it uses the lowest JPEG quality and the lowest resolution target (72 dpi). At /ebook and /printer, Ghostscript re-encoded the JPEGs at about the same quality, so it saved nothing and added a little overhead. If your users upload phone scans, a fixed /ebook call will often hand back a file larger than the one they sent.

Text-heavy LibreOffice export (1,127 KB, 178 pages):

MethodOutputSavedTimePage 1 quality
qpdf (lossless)340 KB70%207 msidentical
gs /ebook349 KB69%448 ms38.0 dB
gs /screen351 KB69%459 ms38.0 dB
gs /printer367 KB67%416 ms38.0 dB
pdf-lib (lossless)377 KB67%239 msidentical

Here the lossless tool wins on every count. It's the smallest file, twice as fast as Ghostscript, and the page is unchanged. Ghostscript's 38 dB isn't from images (there are none). It re-embeds the fonts, so the text renders very slightly differently.

Why a lossless tool saved 70%

We were surprised too, so we looked inside the file. The LibreOffice export has 5,229 objects (pages, fonts, links, structure), and each one is written as plain uncompressed text. About 880 KB of the 1,127 KB file sits outside any compressed stream.

qpdf --object-streams=generate packs those objects into compressed object streams, a feature added in PDF 1.5. Running qpdf with only that flag gave 344 KB. Recompressing the existing streams (--recompress-flate) added nothing on this file. So for office exports, the bloat is structure, not images, and you can remove it without touching a pixel.

The production code

Since the best method depends on the file, don't guess. Run both, keep the smaller one, and fall back to the original:

import { execFile } from 'node:child_process'
import { promisify } from 'node:util'
import { mkdtemp, readFile, rm, stat } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'

const run = promisify(execFile)
const GS = process.env.GHOSTSCRIPT_PATH ?? 'gs'
const QPDF = process.env.QPDF_PATH ?? 'qpdf'
const PRESETS = new Set(['screen', 'ebook', 'printer']) // allowlist: never pass user input straight to gs

export async function compressPdf(input, { preset = 'ebook', lossy = true } = {}) {
  if (!PRESETS.has(preset)) throw new Error(`unknown preset: ${preset}`)
  const dir = await mkdtemp(path.join(tmpdir(), 'pdfc-'))
  try {
    const candidates = [{ name: 'original', file: input }]

    const lossless = path.join(dir, 'lossless.pdf')
    try {
      await run(QPDF, ['--object-streams=generate', '--compress-streams=y', input, lossless], { timeout: 120_000 })
    } catch (e) {
      if (e.code !== 3) throw e // qpdf exit 3 = succeeded with warnings; the output is still written
    }
    candidates.push({ name: 'qpdf', file: lossless })

    if (lossy) {
      const out = path.join(dir, 'lossy.pdf')
      await run(GS, ['-sDEVICE=pdfwrite', '-dCompatibilityLevel=1.6', `-dPDFSETTINGS=/${preset}`,
        '-dNOPAUSE', '-dBATCH', '-dQUIET', '-dSAFER', `-sOutputFile=${out}`, input], { timeout: 120_000 })
      candidates.push({ name: `gs /${preset}`, file: out })
    }

    const sized = await Promise.all(candidates.map(async c => ({ ...c, size: (await stat(c.file)).size })))
    const best = sized.reduce((a, b) => (b.size < a.size ? b : a))
    return { method: best.name, bytes: await readFile(best.file), sizes: Object.fromEntries(sized.map(c => [c.name, c.size])) }
  } finally {
    await rm(dir, { recursive: true, force: true })
  }
}

On our three files it picked a different winner each time, which is the point:

FilePickedResult
photos-lossless.pdfgs /ebook7,402 KB to 389 KB
text-report.pdfqpdf1,127 KB to 344 KB, lossless
photos-jpeg.pdforiginalNothing beat the input, so the user gets their file back unchanged instead of a bigger one

A few things that matter on a real server:

  1. Use execFile with an argument array, not exec with a string. File names and options never reach a shell. If users can choose the preset, check it against an allowlist like PRESETS above.
  2. Pass -dSAFER to Ghostscript. PDFs can contain PostScript, and -dSAFER stops it from reading or writing files on your server. It's the default in Ghostscript 9.50 and later, but being explicit costs nothing.
  3. Treat qpdf exit code 3 as success. It means "done, with warnings". Damaged-but-readable PDFs trigger it all the time.
  4. Always set a timeout. A malformed 500-page PDF can keep Ghostscript busy for minutes. On a small 1 vCPU server, one stuck job blocks everyone else.

What about pdf-lib?

pdf-lib is great for building and editing PDFs in pure JavaScript, and it ran in 30 ms on a 7 MB file. But it can't recompress images, and on the text export its object streams saved slightly less than qpdf's (377 KB vs 340 KB). Use it when you can't install binaries, for example in serverless functions, and accept that it will only help on structure-heavy files.

Try it without code

If you just need one file smaller, our free Compress PDF tool does it online with no sign-up.

// no code needed?
Do it online with Horizech Studio Compress PDF. Free, no sign-up.
open the tool ↗
⚡
Written by Horizech Team

Part of the team at Horizech — we build Flutter apps, AI integrations, web platforms, and games. If you want this done for you, get in touch.

hire us →
← all posts