Python: Compress PDF Documents

2024-05-20 01:17:35 Written by  support iceblue
Rate this item
(0 votes)

PDF has become the standard for sharing documents across various platforms and devices. However, large PDF files can be cumbersome to share, especially when dealing with limited storage space or slow internet connections. Compressing PDF files is an essential skill to optimize file size and ensure seamless document distribution. In this article, we will demonstrate how to compress PDF documents in Python using Spire.PDF for Python.

Install Spire.PDF for Python

This scenario requires Spire.PDF for Python. It can be easily installed in your Windows through the following pip command.

pip install Spire.PDF

If you are unsure how to install, please refer to this tutorial: How to Install Spire.PDF for Python on Windows

Compress PDF Documents in Python

PDF files are often large when they include high-resolution images or embedded fonts. To reduce the size of PDF files, consider compressing the images and fonts contained within them. The following steps explain how to compress PDF documents by compressing fonts and images using Spire.PDF for Python:

  • Create a PdfCompressor object to compress a specified PDF file at a given path.
  • Get the OptimizationOptions object using PdfCompressor.OptimizationOptions property.
  • Enable font compression using OptimizationOptions.SetIsCompressFonts(True) method.
  • Set image quality using OptimizationOptions.SetImageQuality(imageQuality:ImageQuality) method.
  • Enable image resizing using OptimizationOptions.SetResizeImages(True) method.
  • Enable image compression using OptimizationOptions.SetIsCompressImage(True) method.
  • Compress the PDF file and save the compressed version to a new file using PdfCompressor.CompressToFile() method.
  • Python
from spire.pdf.common import *
from spire.pdf import *

 # Create a PdfCompressor object to compress the specified PDF file at the given path
compressor = PdfCompressor("C:/Users/Administrator/Documents/Example.pdf")

# Get the OptimizationOptions object
compression_options = compressor.OptimizationOptions

# Enable font compression
compression_options.SetIsCompressFonts(True)
# Enable font unembedding
# compression_options.SetIsUnembedFonts(True)

# Set image quality
compression_options.SetImageQuality(ImageQuality.Medium)
# Enable image resizing
compression_options.SetResizeImages(True)
# Enable image compression
compression_options.SetIsCompressImage(True)

# Compress the PDF file and save the compressed version to a new file
compressor.CompressToFile("Compressed.pdf")

Python: Compress PDF Documents

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Additional Info

  • tutorial_title:
Last modified on Wednesday, 29 May 2024 02:16