Skip to main content

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.

Compress PDF Files with Python

Environment Setup

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

pip install Spire.PDF

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)

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)

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

options.SetIsUnembedFonts(True)

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()

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

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)

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}")

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 TypeRecommended Approach
Scanned PDFImage compression
PDF with many screenshots or photosImage compression and resizing
Text-heavy reportDocument and font compression
PDF with many embedded fontsFont compression
PDF edited and saved many timesDisable incremental updates and resave
PDF with mixed text, images, and fontsCombine 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.

Comments

Popular posts from this blog

3 Ways to Generate Word Documents from Templates in Java

A template is a document with pre-applied formatting like styles, tabs, line spacing and so on. You can quickly generate a batch of documents with the same structure based on the template. In this article, I am going to show you the different ways to generate Word documents from templates programmatically in Java using Free Spire.Doc for Java library. Prerequisite First of all, you need to add needed dependencies for including Free Spire.Doc for Java into your Java project. There are two ways to do that. If you use maven, you need to add the following code to your project’s pom.xml file. <repositories>               <repository>                   <id>com.e-iceblue</id>                   <name>e-iceblue</name>...

Insert and Extract OLE objects in Word in Java

You can use OLE (Object Linking and Embedding) to include content from other programs, such as another Word document, an Excel or PowerPoint document to an existing Word document. This article demonstrates how to insert and extract embedded OLE objects in a Word document in Java by using Free Spire.Doc for Java API.   Add dependencies First of all, you need to add needed dependencies for including Free Spire.Doc for Java into your Java project. There are two ways to do that. If you use maven, you need to add the following code to your project’s pom.xml file.     <repositories>               <repository>                   <id>com.e-iceblue</id>                   <name>e-iceblue</name>    ...

Simple Java Code to Convert Excel to PDF in Java

This article demonstrates a simple solution to convert an Excel file to PDF in Java by using free Excel API – Free Spire.XLS for Java . The following examples illustrate two possibilities to convert Excel to PDF:      Convert the whole Excel file to PDF     Convert a particular Excel Worksheet to PDF Before start with coding, you need to Download Free Spire.XLS for Java package , unzip it and import Spire.Xls.jar file from the lib folder in your project as a denpendency. 1. Convert the whole Excel file to PDF Spire.XLS for Java provides saveToFile method in Workbook class that enables us to easily save a whole Excel file to PDF. import com.spire.xls.FileFormat; import com.spire.xls.Workbook; public class ExcelToPDF {     public static void main(String[] args){         //Create a Workbook         Workbook workbook = new Workbook();   ...