IRONSOFTWAREHOME

How to Compress PDF Files in Python

Curtis Chau
Curtis Chau
Updated: August 2, 2026

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
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?

pip install ironpdf

Please note: IronPDF 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.

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.

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.

Tips: For 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.

Important: Always 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.

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 note: IronPDF'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

What is the purpose of the CompressImages method in IronPDF?

The CompressImages method in IronPDF is used to reduce the size of PDF files by compressing embedded images with adjustable quality settings. This helps optimize storage and speed up document sharing without sacrificing readability.

How can you install IronPDF for Python?

To install IronPDF for Python, you need to run 'pip install ironpdf'. Note that IronPDF for Python runs on top of the IronPDF .NET library, which requires the .NET 6.0 SDK. You should download the .NET 6.0 SDK from the official Microsoft website before the installation.

What are the differences in quality settings when using CompressImages in IronPDF?

The CompressImages method allows quality settings between 1 to 100. High-quality settings (70-90) are suitable for printing and formal distribution, medium (50-70) for web delivery and email attachments, and aggressive compression (30-50) for internal archives and long-term storage.

Can IronPDF compress PDFs generated from HTML?

Yes, IronPDF can compress PDFs generated from HTML. It uses the same compression API for both HTML to PDF conversions and existing documents, allowing flexibility in file management.

How does IronPDF handle scale-to-visible-size compression?

In addition to quality-based compression, IronPDF's CompressImages method offers a scale-to-visible-size option that resamples images to their rendered dimensions on PDF pages. This can further reduce file sizes but may affect image clarity if the document is resized later.

Is it possible to apply batch compression to multiple PDF files with IronPDF?

Yes, IronPDF supports batch compression. You can iterate over PDF files in a folder, compress each file using the CompressImages method, and save the results. This process can be wrapped into a reusable utility function.

What is the recommended compression quality for web or email delivery?

For web delivery and email attachments, a medium quality range of 50-70 is recommended. This provides a balance between file size reduction and maintaining image clarity, significantly improving load times and deliverability.

How can you verify the effectiveness of PDF compression in Python?

You can verify PDF compression effectiveness by comparing file sizes before and after compression. Use Python's os.path.getsize function to check the byte count of both versions and calculate the reduction percentage.

Why should you keep the original uncompressed PDF file accessible?

The original uncompressed PDF should be kept accessible because compression is lossy for images; you cannot recover the original image data from the compressed file. This ensures you have access to higher quality files if needed.

What are the next steps after using CompressImages for PDF compression?

After compressing PDFs with CompressImages, you can explore other IronPDF features such as HTML to PDF conversion, digital signatures, form handling, and document merging. A free trial allows you to test the full feature set before choosing a licensing option.

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.9just released

Get your FREE

30-day Trial Key instantly.

bullet_checkedNo credit card or account creation required
bullet_testTest in production
without watermarks
bullet_calendar30 days fully
functional product
bullet_support24/5 technical
support during trial
Get your free 30-day Trial Key instantly.
No credit card or account creation required
Python Module Download for PDF
Install with pip

Version: 2026.9

  1. Download and install Python 3.7+.
  2. Install pip from pypi.org if it isn't installed already.
  3. Execute the above command in the terminal.
Python PDF Module
Download Module

Version: 2026.9

Manually install into your project

  1. Download the package
  2. Run this command from the terminal
    pip install ironpdf-2026.9-py37-none-win_amd64.whi

Licenses from $999

Key in blue circle

Get your free 30-day Trial Key instantly.

Your trial license will be sent to your email address

No limitations. 100% unlocked. No credit card.

bullet_checkedNo credit card or account creation requiredNo limitations. 100% unlocked. No credit card.
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
Book your free Live Demo
Booking Badge

Trusted by Millions of Engineers Worldwide

Iron Software's customer logos
Get Your No-Obligation Consult
Complete the form below or email sales@ironsoftware.com
Your details will always be kept confidential.
Trusted by Millions of Engineers Worldwide
Iron Software's customer logos
Get your free 30-day Trial Key instantly.
No credit card or account creation required