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.
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:
| File | Pages | Size | What's inside |
|---|---|---|---|
photos-lossless.pdf | 8 | 7,402 KB | Photos embedded as PNG (lossless), like many screenshot and scan-to-PDF exports |
photos-jpeg.pdf | 8 | 1,270 KB | The same photos embedded as JPEG quality 95, like phone "scan document" apps |
text-report.pdf | 178 | 1,127 KB | A 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):
| Method | Output | Saved | Time | Page 1 quality |
|---|---|---|---|---|
| gs /screen | 252 KB | 97% | 331 ms | 35.4 dB |
| gs /ebook | 389 KB | 95% | 298 ms | 35.4 dB |
| gs /printer | 743 KB | 90% | 254 ms | 38.6 dB |
| qpdf (lossless) | 7,398 KB | 0% | 567 ms | identical |
| pdf-lib (lossless) | 7,402 KB | 0% | 30 ms | identical |
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):
| Method | Output | Saved | Time | Page 1 quality |
|---|---|---|---|---|
| gs /screen | 646 KB | 49% | 176 ms | 51.3 dB |
| gs /ebook | 1,274 KB | 0% (slightly bigger) | 102 ms | 51.3 dB |
| gs /printer | 1,277 KB | -1% (bigger) | 112 ms | 51.3 dB |
| qpdf (lossless) | 1,270 KB | 0% | 13 ms | identical |
| pdf-lib (lossless) | 1,270 KB | 0% | 17 ms | identical |
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):
| Method | Output | Saved | Time | Page 1 quality |
|---|---|---|---|---|
| qpdf (lossless) | 340 KB | 70% | 207 ms | identical |
| gs /ebook | 349 KB | 69% | 448 ms | 38.0 dB |
| gs /screen | 351 KB | 69% | 459 ms | 38.0 dB |
| gs /printer | 367 KB | 67% | 416 ms | 38.0 dB |
| pdf-lib (lossless) | 377 KB | 67% | 239 ms | identical |
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:
| File | Picked | Result |
|---|---|---|
| photos-lossless.pdf | gs /ebook | 7,402 KB to 389 KB |
| text-report.pdf | qpdf | 1,127 KB to 344 KB, lossless |
| photos-jpeg.pdf | original | Nothing 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:
- Use
execFilewith an argument array, notexecwith a string. File names and options never reach a shell. If users can choose the preset, check it against an allowlist likePRESETSabove. - Pass
-dSAFERto Ghostscript. PDFs can contain PostScript, and-dSAFERstops it from reading or writing files on your server. It's the default in Ghostscript 9.50 and later, but being explicit costs nothing. - Treat qpdf exit code 3 as success. It means "done, with warnings". Damaged-but-readable PDFs trigger it all the time.
- 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.
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.