DEV Community

Cover image for Compress PDF Files with Python: Images, Fonts & Document Content
Leon Davis
Leon Davis

Posted on

Compress PDF Files with Python: Images, Fonts & Document Content

Large PDF files are not always caused by a high page count. High-resolution images, scanned pages, embedded fonts, and insufficiently compressed document content can all increase file size significantly.

When PDFs need to be sent by email, uploaded to a website, or stored in bulk, the best compression method depends on what the file contains. For example, scanned PDFs usually benefit most from image compression, while text-heavy documents may be reduced by compressing fonts and document content.

This article shows how to compress images, fonts, and document content in PDF files with Python, as well as how to process multiple PDFs in a folder.

Environment Setup

To run the code examples below, first install the required Python module for PDF processing:

pip install Spire.PDF
Enter fullscreen mode Exit fullscreen mode

Compress Images in a PDF with Python

For scanned documents, product manuals, screenshots, and similar PDFs, images often account for most of the file size.

You can reduce the size of these files by compressing the images and adjusting their quality:

from spire.pdf import *

input_file = "input.pdf"
output_file = "compressed_images.pdf"

# Load the PDF file
compressor = PdfCompressor(input_file)

# Get compression options
options = compressor.OptimizationOptions

# Enable image resizing
options.SetResizeImages(True)

# Enable image compression
options.SetIsCompressImage(True)

# Set image quality
options.SetImageQuality(ImageQuality.Medium)

# Save the compressed PDF
compressor.CompressToFile(output_file)
Enter fullscreen mode Exit fullscreen mode

SetIsCompressImage(True) enables image compression, while SetResizeImages(True) allows image dimensions to be adjusted during compression.

Image quality can be set to low, medium, or high. For PDFs mainly intended for on-screen viewing, Medium is a reasonable starting point.

For engineering drawings, contract scans, or documents that need to remain readable when zoomed in, avoid starting with a low image quality setting. Excessive compression may make text, lines, or other fine details difficult to read.

Compress Embedded Fonts in a PDF

PDF files often embed fonts so that text is displayed consistently across different devices.

If a document uses several fonts, or if the embedded font files are relatively large, font data can also contribute to the overall file size.

The following example compresses embedded fonts:

from spire.pdf import *

input_file = "input.pdf"
output_file = "compressed_fonts.pdf"

# Load the PDF file
compressor = PdfCompressor(input_file)

# Get compression options
options = compressor.OptimizationOptions

# Compress embedded fonts
options.SetIsCompressFonts(True)

# Save the compressed PDF
compressor.CompressToFile(output_file)
Enter fullscreen mode Exit fullscreen mode

If you need to reduce the file size further, embedded fonts can also be removed:

options.SetIsUnembedFonts(True)
Enter fullscreen mode Exit fullscreen mode

This option should be used with caution.

If the system opening the PDF does not have the required font installed, the PDF viewer may substitute another font. This can affect text appearance and, in some cases, page layout.

For PDFs that need to be shared across different devices, printed, or archived, it is usually safer to keep fonts embedded and only compress the font data.

Compress PDF Document Content

In addition to images and fonts, the PDF document itself can also be compressed.

The following example disables incremental updates and sets the document compression level to the highest level:

from spire.pdf import *

input_file = "input.pdf"
output_file = "compressed.pdf"

# Load the PDF file
pdf = PdfDocument()
pdf.LoadFromFile(input_file)

# Disable incremental updates
pdf.FileInfo.IncrementalUpdate = False

# Set the document compression level
pdf.CompressionLevel = PdfCompressionLevel.Best

# Save the compressed PDF
pdf.SaveToFile(output_file)

pdf.Close()
Enter fullscreen mode Exit fullscreen mode

The IncrementalUpdate setting is worth noting.

When a PDF is edited and saved, incremental updates can append new changes to the end of the existing file instead of rewriting the entire document.

This preserves previous data, but after repeated edits and saves, the file may contain additional data that is no longer needed, causing the file size to grow.

Setting:

pdf.FileInfo.IncrementalUpdate = False
Enter fullscreen mode Exit fullscreen mode

forces the document to be rewritten when saved instead of continuing to append incremental changes.

This approach is more useful for PDFs that mainly contain text, vector graphics, and other document content. If the file consists mostly of scanned images, document compression alone may not make a noticeable difference, and image compression should also be applied.

Compress Images and Fonts Together

For PDFs that contain both images and embedded fonts, you can enable both compression options in the same operation:

from spire.pdf import *

input_file = "input.pdf"
output_file = "compressed.pdf"

# Load the PDF file
compressor = PdfCompressor(input_file)

# Get compression options
options = compressor.OptimizationOptions

# Compress images
options.SetResizeImages(True)
options.SetIsCompressImage(True)
options.SetImageQuality(ImageQuality.Medium)

# Compress fonts
options.SetIsCompressFonts(True)

# Save the compressed PDF
compressor.CompressToFile(output_file)
Enter fullscreen mode Exit fullscreen mode

This approach keeps fonts embedded while reducing both image and font data, making it suitable for many general-purpose documents.

For image-heavy PDFs, you can test different image quality levels and compare the resulting file size and visual quality before deciding which setting is appropriate.

Batch Compress Multiple PDF Files

If you need to process multiple PDFs, you can loop through a folder and apply the same compression settings to each file:

import os
from spire.pdf import *

input_folder = "PDFs"
output_folder = "Compressed"

os.makedirs(output_folder, exist_ok=True)

for file_name in os.listdir(input_folder):

    if not file_name.lower().endswith(".pdf"):
        continue

    input_file = os.path.join(input_folder, file_name)
    output_file = os.path.join(output_folder, file_name)

    # Load the PDF file
    compressor = PdfCompressor(input_file)

    # Get compression options
    options = compressor.OptimizationOptions

    # Compress images
    options.SetResizeImages(True)
    options.SetIsCompressImage(True)
    options.SetImageQuality(ImageQuality.Medium)

    # Compress fonts
    options.SetIsCompressFonts(True)

    # Save the compressed PDF
    compressor.CompressToFile(output_file)

    print(f"Compressed: {file_name}")
Enter fullscreen mode Exit fullscreen mode

This approach is useful for processing archived documents, preparing files before upload, or compressing PDFs as part of a batch workflow.

Why Does PDF Compression Sometimes Make Little Difference?

The result depends heavily on the original PDF content.

For example, if the images in a PDF are already heavily compressed, recompressing them may save very little additional space.

Similarly, if a PDF mainly contains simple text and its fonts, images, and content streams have already been optimized, the file size may not change much after another compression pass.

The following table provides a simple guide:

PDF Type Recommended Approach
Scanned PDF Image compression
PDF with many screenshots or photos Image compression and resizing
Text-heavy report Document and font compression
PDF with many embedded fonts Font compression
PDF edited and saved many times Disable incremental updates and resave
PDF with mixed text, images, and fonts Combine multiple compression methods

After compression, do not compare file sizes alone. Open the output PDF and check the text, images, and page layout as well.

This is especially important when lowering image quality or removing embedded fonts.

Conclusion

For scanned and image-heavy documents, image compression and resizing are usually the most effective. For text-heavy PDFs, compressing fonts and document content may be more useful. If a PDF has been edited and saved repeatedly, disabling incremental updates before resaving may also help reduce unnecessary file data.

In practice, it is better to start with moderate compression settings and then adjust them based on the resulting file size and document quality.

Top comments (0)