How to Compress PDF Files Using Python | IronPDF

How to Compress PDF Files in Python

IronPDF's CompressImages method enables Python developers to reduce PDF file sizes by compressing images with customizable quality settings, helping optimize storage and improve document sharing efficiency without sacrificing readability.

Quickstart: Compress PDF Files in Python

:title=quickstart
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
:title=quickstart
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 due to their large file sizes. This creates challenges when sharing or uploading PDF documents and managing storage resources efficiently. To overcome this obstacle, you can employ PDF compression techniques to reduce the size of PDF files.

In this guide, we will demonstrate how to use IronPDF to compress PDF files effectively. We will present practical code examples that you can readily incorporate into your projects, enabling you to compress PDF files and optimize their size efficiently. Whether you're working with HTML to PDF conversions or existing PDF documents, IronPDF provides robust compression capabilities.

What Is IronPDF and Why Use It for PDF Compression?

IronPDF is a comprehensive Python PDF library that provides extensive PDF manipulation capabilities. Whether you're creating PDFs from scratch, manipulating, compressing, or reading PDFs, IronPDF offers the necessary tools. It provides an array of features to streamline your PDF workflows.

One key feature of IronPDF is its compression capability. It enables you to compress existing PDFs, effectively reducing file sizes while maintaining high PDF quality. This is particularly useful when dealing with large documents that require quick sharing over the internet or via email. The compression functionality works seamlessly with PDFs generated from various sources, including those created through HTML to PDF conversion.

IronPDF's compression algorithm intelligently optimizes images within PDF documents, which are often the primary contributors to large file sizes. By adjusting the image quality and resolution, you can achieve significant file size reductions while preserving document readability and visual integrity. This makes it an ideal solution for businesses that need to manage large volumes of PDF documents efficiently.

How Do I Install IronPDF in Python?

To install IronPDF using pip, simply use the following command:

 pip install ironpdf

Please noteIronPDF for Python relies on the IronPDF .NET library, specifically .NET 6.0, as its underlying technology. Therefore, it is necessary to have the .NET 6.0 SDK installed on your machine in order to use IronPDF for Python. Download the .NET 6.0 SDK from the official Microsoft website.

After installation, you may need to configure your license key if you're using IronPDF in a production environment. The library offers a free trial period for development and testing purposes.

How Can I Compress PDF Files Using IronPDF?

The following Python code utilizes the IronPDF library to compress PDF documents effectively. This example demonstrates both basic compression and advanced compression with resolution scaling options.

from ironpdf import PdfDocument

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

# Compress images in the PDF with a quality setting of 60 (out of 100)
# Lower numbers reduce quality to increase compression
pdf.CompressImages(60)
pdf.SaveAs("document_compressed.pdf")

# Compress images with an additional option to scale down image resolution according to their visible size in the PDF
# This may cause distortion depending on the image configurations
pdf.CompressImages(90, True)
pdf.SaveAs("Compressed.pdf")
from ironpdf import PdfDocument

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

# Compress images in the PDF with a quality setting of 60 (out of 100)
# Lower numbers reduce quality to increase compression
pdf.CompressImages(60)
pdf.SaveAs("document_compressed.pdf")

# Compress images with an additional option to scale down image resolution according to their visible size in the PDF
# This may cause distortion depending on the image configurations
pdf.CompressImages(90, True)
pdf.SaveAs("Compressed.pdf")
PYTHON

What Do the Compression Parameters Mean?

  • Loading the PDF: The code reads an existing PDF document called "Image based PDF.pdf" from the relative directory. You can also load PDFs from URLs or byte arrays.
  • CompressImages: The CompressImages method is used to compress images in the PDF. The quality parameter ranges from 1 to 100, where 100 retains the original quality.
  • Saving the Compressed PDF: The compressed version is saved as "document_compressed.pdf".
  • Alternative Approach: The second call to CompressImages includes an optional parameter that scales down the image resolution based on its visible size. The resulting PDF is saved as "Compressed.pdf".

Compare the compressed file with the original PDF to observe the difference in file size and image quality. For more advanced compression scenarios, check out our PDF compression examples.

Advanced Compression Techniques

For more sophisticated compression needs, you can combine IronPDF's compression features with other optimization techniques:

from ironpdf import PdfDocument

# Load a PDF that may have been created from HTML
pdf = PdfDocument("large_report.pdf")

# Apply aggressive compression for maximum file size reduction
# Quality of 40 provides significant compression while maintaining readability
pdf.CompressImages(40)

# You can also compress after merging multiple PDFs
# This is useful when consolidating documents
pdf.SaveAs("highly_compressed.pdf")

# For PDFs with mixed content (images and text), consider:
# - Higher quality (70-80) for documents with important diagrams
# - Lower quality (30-50) for documents primarily containing photos
# - Medium quality (50-70) for general-purpose compression
from ironpdf import PdfDocument

# Load a PDF that may have been created from HTML
pdf = PdfDocument("large_report.pdf")

# Apply aggressive compression for maximum file size reduction
# Quality of 40 provides significant compression while maintaining readability
pdf.CompressImages(40)

# You can also compress after merging multiple PDFs
# This is useful when consolidating documents
pdf.SaveAs("highly_compressed.pdf")

# For PDFs with mixed content (images and text), consider:
# - Higher quality (70-80) for documents with important diagrams
# - Lower quality (30-50) for documents primarily containing photos
# - Medium quality (50-70) for general-purpose compression
PYTHON

What Does the PDF Look Like Before Compression?

PDF file in Edge browser showing 458 KB file size before compression

How Does the PDF Appear After Compression?

Compressed PDF file showing 357 KB size in Windows Explorer after IronPDF compression

As you can see from the comparison, the compression achieved a significant reduction from 458 KB to 357 KB (approximately 22% reduction) while maintaining visual quality. This demonstrates the effectiveness of IronPDF's compression algorithm for real-world applications.

Best Practices for PDF Compression

When working with PDF compression in Python, consider these best practices:

  1. Test Different Quality Levels: Start with quality 70-80 and adjust based on requirements. Text documents can use lower quality without degradation.

  2. Consider Your Use Case: For printing, use higher quality (80-95). For web or email, lower settings (50-70) suffice.

  3. Batch Processing: Implement batch processing for multiple PDFs:
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 PDFs
        output_folder: Path to save compressed PDFs
        quality: Compression quality (1-100)
    """
    # Ensure output folder exists
    os.makedirs(output_folder, exist_ok=True)

    # Process each PDF file
    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:
                # Load and compress the PDF
                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}")
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 PDFs
        output_folder: Path to save compressed PDFs
        quality: Compression quality (1-100)
    """
    # Ensure output folder exists
    os.makedirs(output_folder, exist_ok=True)

    # Process each PDF file
    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:
                # Load and compress the PDF
                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
  1. Monitor File Size vs. Quality: Review compressed output to ensure quality meets standards. Some images need higher settings.

  2. Combine Optimization Techniques: Use compression with other features like merging PDFs before compression.

Why Should I Choose IronPDF for PDF Compression?

IronPDF provides reliable PDF compression capabilities for Python developers. It offers comprehensive features including page rotation, HTML to PDF conversion, and image manipulation. These combined capabilities make IronPDF an excellent choice for developers requiring complete PDF manipulation functionality.

Starting from $799, IronPDF provides developers with accessible licensing options, ensuring quality software at reasonable costs. With its robust PDF optimization functionality, IronPDF delivers efficient PDF compression capabilities for various applications.

The library's extensive documentation and code examples simplify implementing compression features in your Python applications. Whether you're building a document management system, optimizing PDFs for web delivery, or reducing storage costs, IronPDF provides the necessary tools for success.

Frequently Asked Questions

How do I install the necessary library to compress PDFs in Python?

To compress PDFs in Python using IronPDF, install the library with pip by running: pip install ironpdf. This will give you access to the CompressImages method and other PDF manipulation features.

What is the basic code structure for compressing a PDF file?

The basic structure involves loading your PDF with PdfDocument, calling the CompressImages method with a quality parameter (1-100), and saving the compressed file using SaveAs. For example: pdf = PdfDocument('your-file.pdf'), pdf.CompressImages(60), pdf.SaveAs('compressed.pdf').

How does the quality parameter affect PDF compression?

The CompressImages method accepts a quality parameter from 1 to 100, where lower values result in smaller file sizes but reduced image quality, while higher values maintain better quality but larger file sizes. IronPDF intelligently optimizes images within the PDF to achieve the desired compression level.

Can I compress PDFs created from HTML conversions?

Yes, IronPDF's compression functionality works seamlessly with PDFs generated from various sources, including those created through HTML to PDF conversion. You can compress any PDF regardless of how it was originally created.

What makes PDF compression particularly useful for developers?

PDF compression with IronPDF is especially valuable when dealing with large documents that need quick sharing over the internet or via email. It helps optimize storage resources and improves document sharing efficiency while maintaining readability.

Does compressing a PDF affect its readability?

IronPDF's compression algorithm is designed to preserve document readability and visual integrity while reducing file size. By adjusting the quality parameter, you can balance between file size reduction and maintaining acceptable document quality.

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: 2025.9 just released