How to Compress PDF Files Using Python | IronPDF

How to Compress PDF Files in Python

IronPDF's CompressImages method lets Python developers reduce PDF file sizes by compressing embedded images with adjustable quality settings, helping optimize storage and speed up document sharing without sacrificing readability.

Quickstart: Compress PDF Files in Python

:path=/static-assets/ironpdf-python/content-code-examples/how-to/python-compress-pdf/quickstart.py
from ironpdf import PdfDocument

# 1. Install IronPDF: pip install ironpdf
# 2. Load your PDF
pdf = PdfDocument("your-file.pdf")
# 3. Compress images (quality: 1-100)
pdf.CompressImages(60)
# 4. Save compressed PDF
pdf.SaveAs("compressed.pdf")
# 5. Adjust quality parameter to balance size vs quality
// THIS CODE SNIPPET IS NOT AVAILABLE!
from ironpdf import PdfDocument

# 1. Install IronPDF: pip install ironpdf
# 2. Load your PDF
pdf = PdfDocument("your-file.pdf")
# 3. Compress images (quality: 1-100)
pdf.CompressImages(60)
# 4. Save compressed PDF
pdf.SaveAs("compressed.pdf")
# 5. Adjust quality parameter to balance size vs quality
PYTHON

PDF files are widely used for document storage and sharing, but they can become cumbersome at large file sizes. Uploading or emailing a 10 MB report is noticeably slower than sharing a 2 MB equivalent, and storage costs accumulate when document volumes are high. PDF compression addresses this by reducing file size while keeping content readable.

This guide shows how to use IronPDF to compress PDF files in Python. Practical code examples cover both standard image compression and advanced resolution-based compression, so you can choose the approach that fits your pipeline. Whether working with HTML to PDF conversions or existing documents, the same compression API applies.

What Is IronPDF and Why Use It for PDF Compression?

IronPDF is a Python PDF library that handles creation, reading, editing, and optimization of PDF documents. It works with files generated from scratch, converted from HTML, or loaded from disk. Its compression API targets images, which are the primary contributor to large PDF sizes.

The CompressImages method accepts a quality integer from 1 to 100 and an optional boolean that scales images down to their visible resolution. This dual-parameter design lets you tune compression precisely: a high-traffic reporting dashboard might use quality 70 to keep visuals sharp, while an internal archive system might use quality 40 to maximize storage savings. The library handles all encoding internally, so no additional dependencies are required.

IronPDF is part of the Iron Suite, which covers document creation, barcode processing, OCR, and ZIP archiving, all from a shared Python installation. For developers already using IronPDF to create PDFs from scratch, compression slots in as a natural follow-on step before saving or distributing files.

How Do You Install IronPDF in Python?

:path=/static-assets/ironpdf-python/content-code-examples/how-to/python-compress-pdf/install.sh
:ProductInstall
// THIS CODE SNIPPET IS NOT AVAILABLE!
:ProductInstall
SHELL

Please noteIronPDF for Python runs on top of the IronPDF .NET library, which requires the .NET 6.0 SDK. Download the .NET 6.0 SDK from the official Microsoft website before running the pip install.

After installation, configure your license key for production environments. IronPDF includes a free 30-day trial that covers all features, including compression, with no credit card required. The PyPI package page lists the latest release notes and dependency details.

How Do You Compress PDF Files Using IronPDF?

Pass a quality integer to CompressImages to reduce the size of embedded images across the entire document. Lower integers produce smaller files at the cost of image fidelity; higher integers preserve more detail. The example below shows both a standard compression call and an advanced call that also scales images down to their visible size.

:path=/static-assets/ironpdf-python/content-code-examples/how-to/python-compress-pdf/compress-basic.py
from ironpdf import PdfDocument

# Load the PDF document from a file
pdf = PdfDocument("Image based PDF.pdf")

# Compress images to quality 60 (lower numbers increase compression)
pdf.CompressImages(60)
pdf.SaveAs("document_compressed.pdf")

# Advanced: also scale images down to their visible size in the PDF
# Note: scaling can affect image clarity if pages are resized later
pdf.CompressImages(90, True)
pdf.SaveAs("Compressed.pdf")
// THIS CODE SNIPPET IS NOT AVAILABLE!
from ironpdf import PdfDocument

# Load the PDF document from a file
pdf = PdfDocument("Image based PDF.pdf")

# Compress images to quality 60 (lower numbers increase compression)
pdf.CompressImages(60)
pdf.SaveAs("document_compressed.pdf")

# Advanced: also scale images down to their visible size in the PDF
# Note: scaling can affect image clarity if pages are resized later
pdf.CompressImages(90, True)
pdf.SaveAs("Compressed.pdf")
PYTHON

What Do the Compression Parameters Mean?

CompressImages accepts two parameters:

  • Quality (required): An integer from 1 to 100. A value of 100 retains original image quality with no compression applied. Values between 40 and 80 cover most practical use cases, with 60 being a common starting point for general-purpose documents.
  • Scale to visible size (optional): A boolean that defaults to False. When True, each image is resampled to match its rendered dimensions on the page. This adds a second reduction pass on top of quality compression, producing smaller files. Note that pages scaled or printed at higher DPI afterward may show artifacts.

After saving, compare the compressed file against the original in any PDF viewer to confirm the quality meets your requirements. For additional pattern examples, see the PDF compression examples page.

What Does the PDF Look Like Before Compression?

PDF file open in Microsoft Edge browser displaying 458 KB file size before IronPDF Python compression is applied

How Does the PDF Appear After Compression?

Compressed PDF file entry in Windows Explorer showing 357 KB file size, a 22% reduction from 458 KB using IronPDF CompressImages at quality 60

The comparison shows a reduction from 458 KB to 357 KB (roughly 22%) using quality 60. Files with a higher proportion of photographic content typically achieve larger reductions than files dominated by text or vector graphics.

How Do You Apply Batch Compression to Multiple PDF Files?

Processing a folder of PDF files follows the same API: iterate over each .pdf file, load it with PdfDocument, call CompressImages, and save the result. The function below wraps that pattern into a reusable utility.

:path=/static-assets/ironpdf-python/content-code-examples/how-to/python-compress-pdf/batch-compress.py
import os
from ironpdf import PdfDocument

def batch_compress_pdfs(input_folder, output_folder, quality=60):
    """
    Compress all PDF files in a folder.

    Args:
        input_folder: Path to folder containing source PDFs
        output_folder: Path where compressed PDFs will be saved
        quality: Compression quality (1–100); default is 60
    """
    # Create the output folder if it does not exist
    os.makedirs(output_folder, exist_ok=True)

    for filename in os.listdir(input_folder):
        if filename.endswith(".pdf"):
            input_path = os.path.join(input_folder, filename)
            output_path = os.path.join(output_folder, f"compressed_{filename}")

            try:
                pdf = PdfDocument(input_path)
                pdf.CompressImages(quality)
                pdf.SaveAs(output_path)
                print(f"Compressed: {filename}")
            except Exception as e:
                print(f"Error compressing {filename}: {e}")
// THIS CODE SNIPPET IS NOT AVAILABLE!
import os
from ironpdf import PdfDocument

def batch_compress_pdfs(input_folder, output_folder, quality=60):
    """
    Compress all PDF files in a folder.

    Args:
        input_folder: Path to folder containing source PDFs
        output_folder: Path where compressed PDFs will be saved
        quality: Compression quality (1–100); default is 60
    """
    # Create the output folder if it does not exist
    os.makedirs(output_folder, exist_ok=True)

    for filename in os.listdir(input_folder):
        if filename.endswith(".pdf"):
            input_path = os.path.join(input_folder, filename)
            output_path = os.path.join(output_folder, f"compressed_{filename}")

            try:
                pdf = PdfDocument(input_path)
                pdf.CompressImages(quality)
                pdf.SaveAs(output_path)
                print(f"Compressed: {filename}")
            except Exception as e:
                print(f"Error compressing {filename}: {e}")
PYTHON

The try/except block prevents a single corrupted or password-protected file from halting the entire batch. Logging the filename alongside the exception message makes it easier to identify which files need manual review. For higher-volume pipelines, consider splitting the folder into chunks and processing them in parallel threads.

TipsFor documents that mix photographic images with technical diagrams, run two passes: quality 50 on photographs and quality 85 on diagram-heavy pages. Extract and re-merge using the merge PDFs API to keep each section at its optimal quality level.

What Quality Settings Should You Use for PDF Compression?

The right quality setting depends on how the PDF will be used after compression. Three ranges cover the most common scenarios.

High quality (70–90): Documents destined for printing or formal distribution benefit from staying in this range. Text stays sharp and diagrams remain legible at standard print resolutions. The file size reduction is modest, typically 10–25%, but the output is indistinguishable from the source for most readers.

Medium quality (50–70): This range suits web delivery and email attachments. Photographic content shows minor softening on close inspection, but the reduction in file size (often 25–50%) meaningfully improves load times and email deliverability. Most document management systems and portal uploads work well at quality 60.

Aggressive compression (30–50): Internal archives, long-term storage backups, and documents that will not be printed can use this range. At quality 40, images are noticeably softer, but text rendered by the PDF engine (rather than embedded as images) remains fully crisp. This approach is also appropriate for documents that will be converted to images and resized before display.

ImportantAlways keep the original uncompressed file accessible. Compression is lossy for images; there is no way to recover the original image data from a compressed PDF.

How Do You Verify Compression Results in Python?

Checking the output file size programmatically confirms that compression met your target before the file moves to the next step in a pipeline. Python's built-in os.path.getsize returns the byte count for any file path, so verification requires no additional libraries.

:path=/static-assets/ironpdf-python/content-code-examples/how-to/python-compress-pdf/verify-compression.py
import os
from ironpdf import PdfDocument

# Load and compress the document
pdf = PdfDocument("report.pdf")
original_size = os.path.getsize("report.pdf")

pdf.CompressImages(60)
pdf.SaveAs("report_compressed.pdf")

compressed_size = os.path.getsize("report_compressed.pdf")
reduction_pct = (1 - compressed_size / original_size) * 100

# Report results to confirm compression was effective
print(f"Original:   {original_size / 1024:.1f} KB")
print(f"Compressed: {compressed_size / 1024:.1f} KB")
print(f"Reduction:  {reduction_pct:.1f}%")
// THIS CODE SNIPPET IS NOT AVAILABLE!
import os
from ironpdf import PdfDocument

# Load and compress the document
pdf = PdfDocument("report.pdf")
original_size = os.path.getsize("report.pdf")

pdf.CompressImages(60)
pdf.SaveAs("report_compressed.pdf")

compressed_size = os.path.getsize("report_compressed.pdf")
reduction_pct = (1 - compressed_size / original_size) * 100

# Report results to confirm compression was effective
print(f"Original:   {original_size / 1024:.1f} KB")
print(f"Compressed: {compressed_size / 1024:.1f} KB")
print(f"Reduction:  {reduction_pct:.1f}%")
PYTHON

The output gives a clear reduction percentage that can be logged or checked against a threshold. If the reduction falls below expectations, the document may contain few or no embedded images. In that case, the file size will remain largely unchanged regardless of the quality setting, since CompressImages targets raster images only. Text and vector graphics are unaffected by this method.

Please noteIronPDF's compression targets JPEG encoding for raster images within PDFs. The JPEG compression standard defines the quality-to-size trade-off that the quality parameter controls. Lower values apply more aggressive JPEG quantization, reducing both file size and image detail.

What Are the Next Steps for PDF Compression in Python?

IronPDF's CompressImages method gives Python developers a single, well-scoped API for reducing PDF file sizes. Adjust the quality parameter to balance storage savings against visual fidelity, and add the resolution-scaling boolean for a second reduction pass when output dimensions are fixed. For a broader look at what IronPDF handles, see the Python PDF library overview page.

Start your free trial to test compression alongside IronPDF's full feature set, including HTML to PDF conversion, digital signatures, form handling, and document merging. When the trial period ends, view licensing options to find the plan that fits your deployment.

Ready to see what else IronPDF can do? Explore the full Python PDF tutorial for a walkthrough of IronPDF's core capabilities.

Frequently Asked Questions

How do I install IronPDF to compress PDFs in Python?

Run pip install ironpdf in your terminal. IronPDF for Python requires the .NET 6.0 SDK to be installed first. After installation, import PdfDocument from the ironpdf package to start compressing PDFs.

What is the basic code to compress a PDF file in Python?

Load the file with PdfDocument("your-file.pdf"), call CompressImages(60) with a quality integer from 1 to 100, and save the result using SaveAs("compressed.pdf"). Adjust the quality value to balance file size against image fidelity.

How does the quality parameter affect PDF compression?

The CompressImages quality parameter ranges from 1 to 100. Lower values produce smaller files with more visible image softening. Higher values preserve more detail at the cost of a larger file. Values between 40 and 80 cover most practical use cases, with 60 as a common starting point.

Can I pass a second argument to CompressImages?

Yes. Passing True as the second argument tells IronPDF to resample each image to its visible dimensions on the page before applying quality compression. This adds a second reduction pass and produces smaller files, but pages scaled or printed at higher DPI afterward may show artifacts.

Does PDF compression affect text and vector graphics?

CompressImages targets raster images embedded in the PDF. Text rendered by the PDF engine and vector graphics are not affected by this method, so documents with little or no embedded imagery will show minimal size reduction.

How do I verify the file size reduction in Python?

Use os.path.getsize("compressed.pdf") to retrieve the byte count of the saved file and compare it to the original. Dividing the difference by the original size gives the reduction percentage as a float.

What quality range is best for web delivery?

A quality setting between 50 and 70 suits most web delivery and email scenarios. This range typically reduces file size by 25 to 50 percent while keeping photographic content visually acceptable for on-screen reading.

Curtis Chau
Technical Writer

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.

...

Read More
Ready to Get Started?
Version: 2026.5 just released
Still Scrolling Icon

Still Scrolling?

Want proof fast?
run a sample watch your HTML become a PDF.