How to Compress PDF Files Using Node.js
Large PDF files slow down file transfers, inflate storage costs, and degrade performance in document-heavy applications. IronPDF for Node.js provides the compressSize method, which reduces embedded image quality and optionally rescales images to their visible dimensions in the document, often cutting file size by 50% or more without changing the document structure.
Quickstart: Compress a PDF in Node.js
Install the package, load a PDF, and call compressSize with a quality value between 1 and 100:
```javascript {.line-numbers} //:path=/static-assets/pdf/content-code-examples/how-to/nodejs-compress-pdf/quickstart.js import { PdfDocument } from "@ironsoftware/ironpdf";
// Load an existing PDF const pdf = await PdfDocument.fromFile("report.pdf");
// Compress embedded images to 60% JPEG quality await pdf.compressSize(60);
// Save the result await pdf.saveAs("report-compressed.pdf");
<div class="hsg-featured-snippet">
<h3>Minimal Workflow (5 steps)</h3>
1. Install IronPDF: `npm install @ironsoftware/ironpdf`
2. Import `PdfDocument` from `@ironsoftware/ironpdf`
3. Load the source file with `PdfDocument.fromFile(path)`
4. Call `await pdf.compressSize(quality)` -- quality range 1-100
5. Save the result with `await pdf.saveAs(outputPath)`
</div>
## Why Does PDF File Size Matter for Node.js Applications?
PDF size directly affects two operational concerns: delivery speed and storage cost. A 20 MB report PDF sent over an API endpoint adds measurable latency on mobile connections. In batch processing pipelines that handle thousands of documents daily, even a 30% size reduction compounds into significant storage savings.
IronPDF's `compressSize` method targets the dominant contributor to large PDF files: embedded images. Text and vector graphics compress well at the PDF object level during rendering, but raster images embedded at original resolution account for most of the excess weight in typical business documents. Reducing JPEG quality from the default (often 95-100%) to 60-85% yields the greatest size reduction with the least visible quality loss.
TipsQuality values at or above 80 are generally indistinguishable from the source at normal screen resolution. Reserve values below 60 for archival or preview use cases where file size is the primary constraint.
## How Does the `compressSize` Method Work?
The `compressSize` method accepts two parameters: `quality` (required, integer 1-100) and `scaleImages` (optional, boolean). When `scaleImages` is `false` (the default), the method re-encodes each embedded JPEG at the target quality. When `scaleImages` is `true`, it also downsamples images to match their visible size in the PDF layout, reducing resolution for images rendered at a small scale on the page.
```javascript {.line-numbers}
//:path=/static-assets/pdf/content-code-examples/how-to/nodejs-compress-pdf/compress-with-scaling.js
import { PdfDocument } from "@ironsoftware/ironpdf";
// Load the source document
const pdf = await PdfDocument.fromFile("product-catalog.pdf");
// Compress images to 90% quality and scale down to visible size
await pdf.compressSize(90, true);
// Save the optimized document
await pdf.saveAs("product-catalog-optimized.pdf");The scaleImages argument is particularly effective for PDFs generated from high-DPI scans or from HTML templates that embed images at full resolution regardless of their display size. Enabling it can reduce file size more than adjusting quality alone, without any visible degradation at typical print or screen resolutions.
The method modifies the PdfDocument object in place. If you need to preserve the original, clone the document before calling compressSize, or use separate save paths.
What Quality Setting Should I Use?
The right quality value depends on how the PDF will be used after compression:
- 90-100: Near-lossless. Use when the document will be printed or viewed at full zoom.
- 80-89: High quality, noticeably smaller file. The default starting point for most business documents.
- 60-79: Medium quality. Acceptable for screen display, web delivery, and email attachments.
- Below 60: Low quality. Suited for preview thumbnails, archival copies, or cases where file size is critical.
How Do I Measure the Compression Result in Node.js?
Verifying that compression achieved the expected reduction is straightforward using the Node.js fs module. Read the file size before and after calling compressSize, then compute the ratio to confirm the result meets your application's requirements.
```javascript {.line-numbers} //:path=/static-assets/pdf/content-code-examples/how-to/nodejs-compress-pdf/measure-compression.js import { PdfDocument } from "@ironsoftware/ironpdf"; import { statSync } from "fs";
const inputPath = "annual-report.pdf"; const outputPath = "annual-report-compressed.pdf";
const beforeBytes = statSync(inputPath).size;
const pdf = await PdfDocument.fromFile(inputPath); await pdf.compressSize(75); await pdf.saveAs(outputPath);
const afterBytes = statSync(outputPath).size; const reduction = (((beforeBytes - afterBytes) / beforeBytes) * 100).toFixed(1);
console.log(Before: ${(beforeBytes / 1024).toFixed(1)} KB); console.log(After: ${(afterBytes / 1024).toFixed(1)} KB); console.log(Reduced by ${reduction}%);
The [Node.js `fs.statSync` API](https://nodejs.org/api/fs.html#fsstatsynspath-options) returns a `Stats` object that includes the `size` property in bytes. For production pipelines, log this ratio per document so you can identify outliers where compression did not reduce size as expected -- typically scanned documents already compressed at source.
ImportantSet the `IRONPDF_ENGINE_PATH` environment variable or configure `IronPdfGlobalConfig` before processing files in a server environment. See the [IronPDF Node.js documentation](https://ironpdf.com/nodejs/docs/) for engine setup details.
## How Do I Compress Multiple PDFs in a Batch?
Production applications rarely compress a single document in isolation. The example below processes an array of file paths concurrently using `Promise.all`, which lets the Node.js event loop handle multiple `compressSize` operations without blocking:
```javascript {.line-numbers}
//:path=/static-assets/pdf/content-code-examples/how-to/nodejs-compress-pdf/batch-compress.js
import { PdfDocument } from "@ironsoftware/ironpdf";
import path from "path";
async function compressPdfFiles(inputPaths, quality = 80) {
const results = await Promise.all(
inputPaths.map(async (inputPath) => {
const pdf = await PdfDocument.fromFile(inputPath);
await pdf.compressSize(quality);
const outputPath = inputPath.replace(".pdf", "-compressed.pdf");
await pdf.saveAs(outputPath);
return { input: inputPath, output: outputPath };
})
);
return results;
}
// Usage
const files = ["report-q1.pdf", "report-q2.pdf", "report-q3.pdf"];
const compressed = await compressPdfFiles(files, 75);
compressed.forEach(r => console.log(`Saved: ${r.output}`));Each call to PdfDocument.fromFile and compressSize is independent, making them safe to parallelize. For very large batches (hundreds of files), consider chunking the array to avoid exceeding Node.js memory limits. The Node.js documentation on the event loop explains how Promise.all schedules concurrent I/O without blocking the main thread.
How Do I Combine Compression with Other PDF Operations?
Compression fits naturally into a larger document processing chain. A common pattern is to generate a PDF from HTML, add a watermark or signature, then compress before delivery:
```javascript {.line-numbers} //:path=/static-assets/pdf/content-code-examples/how-to/nodejs-compress-pdf/compress-after-render.js import { PdfDocument, ChromePdfRenderer } from "@ironsoftware/ironpdf";
// Render HTML to PDF const renderer = new ChromePdfRenderer(); const pdf = await renderer.renderHtmlAsPdf("
Amount due: $540.00
");// Compress before saving -- reduces image weight from Chrome-rendered content await pdf.compressSize(85);
// Save the final document await pdf.saveAs("invoice-1042.pdf");
The `ChromePdfRenderer` often embeds background images and CSS-referenced assets at full resolution. Calling `compressSize` after rendering consistently reduces file size for HTML-sourced PDFs. The IronPDF [HTML to PDF tutorial](https://ironpdf.com/nodejs/tutorials/html-to-pdf/) covers renderer configuration in detail.
For documents that also need [digital signatures](https://ironpdf.com/nodejs/examples/digitally-sign-a-pdf/), apply the signature after compression. Signing locks the document's byte stream, and further modification would invalidate the signature.
When working with multi-page documents, merge them with [`PdfDocument.merge()`](https://ironpdf.com/nodejs/examples/merge-pdfs/) before compressing. Compressing the merged result is more efficient than compressing individual files and re-merging.
TipsMerge multi-page documents before compressing. Compressing the merged result is more efficient than compressing individual files and re-merging.
## What Are the Next Steps for PDF Compression in Node.js?
The `compressSize` method covers the most common compression use case: reducing embedded image weight. For specialized scenarios, the IronPDF [PDF compression example](https://ironpdf.com/nodejs/examples/pdf-compression/) provides additional working code samples, and the [API reference](https://ironpdf.com/nodejs/object-reference/api/) documents all available method signatures.
IronPDF also supports converting [images to PDF](https://ironpdf.com/nodejs/examples/image-to-pdf/), [reading PDF text](https://ironpdf.com/nodejs/examples/reading-pdf-text/), and [removing pages from a PDF](https://ironpdf.com/nodejs/examples/remove-page-from-pdf/) -- all operations that integrate with the same `PdfDocument` API. For a complete overview of Node.js PDF capabilities, see the [IronPDF Node.js docs](https://ironpdf.com/nodejs/docs/).
Ready to test compression in your project? [Start your free trial](#trial-license) to run the examples above without a watermark, or [view licensing options](#licensing) for production deployment.
`PdfDocument`Frequently Asked Questions
How do I compress a PDF in Node.js with IronPDF?
Load a PDF using PdfDocument.fromFile(path), call await pdf.compressSize(quality) with a quality value between 1 and 100, then save the result with await pdf.saveAs(outputPath). Install the package first with npm install @ironsoftware/ironpdf.
What does the quality parameter in compressSize control?
The quality parameter (integer 1-100) controls the JPEG re-encoding level for embedded raster images. Values of 80-89 produce high-quality output with noticeable size reduction and are the recommended starting point for most business documents. Values below 60 are suited for archival or preview use cases where file size is the primary constraint.
What is the scaleImages parameter in compressSize?
The optional second parameter scaleImages (boolean, default false) downsamples embedded images to match their visible dimensions in the PDF layout. Setting it to true is effective for PDFs generated from high-DPI scans or HTML templates that embed images at full resolution regardless of their display size.
How much can PDF file sizes be reduced using compressSize?
Reduction depends on the content of the source PDF. Documents with many high-resolution raster images can see reductions of 50% or more. PDFs containing mostly text and vector graphics will see minimal reduction because compressSize targets JPEG image re-encoding specifically.
How do I measure the compression result in Node.js?
Use fs.statSync(path).size to read file size in bytes before and after compression. Compute the ratio as ((before - after) / before) * 100 to get the percentage reduction.





