How to Compress PDF in Python

This quick topic will walk you through how to compress PDF in Python with the help of complete configuration steps including setting up the environment and other information about the necessary classes to be used. You can easily use simple API calls in Python compress PDF file size and save it to disk. You can further customize the PDF compression by using different options exposed by the OptimizationOptions class.

Steps to Compress PDF in Python

  1. Set the IDE to use Aspose.PDF for Python via .NET in order to compress a PDF file
  2. Load the source PDF file from disk using the Document class instance
  3. Instantiate the OptimizationOptions class object to configure the compression of PDF files and set different PDF optimization settings
  4. The OptimizeResources method in Python compress PDF file based on the settings used
  5. Save the compressed PDF file on the disk

The above steps in Python reduce PDF size by following the defined sequence of operations. You will begin the process by adding API references using the pip install and importing the required namespace. The source PDF file will be loaded using the Document class object for compression. You will use OptimizationOptions class instance to set different compression options for PDF including compression of images and PDF image quality. The OptimizeResources method applies the optimization settings to compress the PDF based on selected options before saving the compressed PDF file on the disk.

Code to Compress PDF in Python

The aforementioned example in Python compress PDF size by adopting simple API calls and a few lines of code. The OptimizationOptions class also allows you to set different other compression settings including LinkDuplicateStreams, ImageEncoding, RemovePrivateInfo, MaxResolution, RemoveUnusedObjects, RemoveUnusedStreams and many other settings. If the source PDF file has a content that can be referred to by using the above mentioned settings, it will contribute towards achieving the compression of PDF once these properties are referred.

In this topic, we have learned that in order to compress PDF file programmatically Python based applications can be easily developed. If you want to learn about converting a PDF to PDFA format, refer to the article on how to convert PDF to PDFA format using Python.

 English