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.
Install the package, load a PDF, and call compressSize with a quality value between 1 and 100:
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");
Minimal Workflow (5 steps)
- Install IronPDF:
npm install @ironsoftware/ironpdf - Import
PdfDocumentfrom@ironsoftware/ironpdf - Load the source file with
PdfDocument.fromFile(path) - Call
await pdf.compressSize(quality)-- quality range 1-100 - Save the result with
await pdf.saveAs(outputPath)
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.
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.
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.
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 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.
IRONPDF_ENGINE_PATH environment variable or configure IronPdfGlobalConfig before processing files in a server environment. See the IronPDF Node.js documentation 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:
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:
import { PdfDocument, ChromePdfRenderer } from "@ironsoftware/ironpdf";
// Render HTML to PDF
const renderer = new ChromePdfRenderer();
const pdf = await renderer.renderHtmlAsPdf("<h1>Invoice #1042</h1><p>Amount due: $540.00</p>");
// 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 covers renderer configuration in detail.
For documents that also need digital signatures, 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() 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 provides additional working code samples, and the API reference documents all available method signatures.
IronPDF also supports converting images to PDF, reading PDF text, and removing pages from a 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.
Ready to test compression in your project? Start your free trial to run the examples above without a watermark, or view licensing options for production deployment.
PdfDocument
Frequently Asked Questions
What method does IronPDF use to compress PDF files in Node.js?
IronPDF uses the `compressSize` method to reduce PDF file size by adjusting the quality of embedded images and optionally rescaling them to their visible dimensions.
How much can IronPDF reduce the size of PDF files?
IronPDF's `compressSize` method can reduce file size by 50% or more, depending on the quality and scale settings used for compressing the embedded images.
What parameters does the `compressSize` method accept?
The `compressSize` method accepts two parameters: `quality` (an integer between 1-100) and `scaleImages` (a boolean that is optional and defaults to false).
How does image quality affect PDF compression?
Image quality affects the file size and appearance. Higher quality settings (e.g., 90-100) maintain better image fidelity, while lower settings (e.g., below 60) significantly reduce file size but may affect image clarity.
Can IronPDF compress multiple PDFs simultaneously in a batch process?
Yes, IronPDF allows batch processing using `Promise.all` to handle multiple `compressSize` operations concurrently in Node.js.
What are some use cases for the `scaleImages` parameter?
The `scaleImages` parameter is useful for PDFs created from high-DPI scans or HTML content, as it downscales images to their visible size, further reducing file size without compromising quality.
How is PDF compression measured in IronPDF?
PDF compression can be measured using the Node.js `fs` module to compare file sizes before and after calling `compressSize`, calculating the percentage reduction.
How does IronPDF handle PDF files generated from HTML?
IronPDF can compress images embedded in PDFs generated from HTML using the `ChromePdfRenderer`, reducing file size by optimizing embedded images.
When should you apply digital signatures in relation to compression?
Digital signatures should be applied after compressing a PDF, as any modifications following signing would invalidate the signature.
What resources are available for learning more about PDF compression in IronPDF?
IronPDF offers a detailed PDF compression example and an API reference documenting method signatures to help developers optimize PDF files effectively.

Curtis Chau holds a Bachelor’s degree in Computer Science (Carleton University) and specializes in front-end development with expertise in Node.js, TypeScript, JavaScript, and React. Passionate about crafting intuitive and aesthetically pleasing user interfaces, Curtis enjoys working with modern frameworks and creating well-structured, visually appealing manuals.