Cómo comprimir archivos PDF usando Python | IronPDF

How to Compress PDF Files in Python

This article was translated from English: Does it need improvement?
Translated
View the article in English

PDF files are widely used for document storage and sharing, but they can become cumbersome due to their large file sizes. This can create challenges when it comes to sharing or uploading PDF documents, as well as 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 delve into utilizing IronPDF to compress PDF files effectively. We will present you with practical code examples that you can readily incorporate into your own projects, enabling you to compress PDF files and optimize their size efficiently.

IronPDF: PDF Library

Welcome to the world of IronPDF, a robust and versatile Python PDF library that empowers users to harness the full potential of PDF files. Whether you're creating, manipulating, compressing, or reading PDFs, IronPDF has got you covered. It offers an array of powerful features to streamline your PDF workflows.

One standout feature of IronPDF is its exceptional compression capability. It enables you to compress existing PDFs, effectively reducing file sizes while maintaining impeccable PDF quality. This is particularly advantageous when dealing with large documents that require swift sharing over the internet or via email.

Install IronPDF via Pip

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

 pip install ironpdf

Por favor notaIronPDF 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.

PDF Compression with IronPDF in Python

The below Python code utilizes the IronPDF library to compress PDF documents.

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

Explanation

  • Loading the PDF: The code reads an existing PDF document called "Image based PDF.pdf" from the relative directory.
  • 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".

Feel free to compare the compressed file with the original PDF to observe the difference in file size and image quality.

Before Compression

Original PDF

After Compression

Compressed PDF Output

Conclusion

IronPDF is a cost-effective and powerful tool designed to compress PDF files in Python. It offers a wide range of features, including page rotation, HTML to PDF conversion, and image manipulation. These combined capabilities make IronPDF an excellent choice for developers who require a comprehensive and budget-friendly solution for compressing PDFs.

Starting from just $799, IronPDF provides developers with an affordable licensing option, ensuring access to high-quality software without breaking the bank. With its reliable and robust PDF optimization functionality, IronPDF offers a hassle-free solution for developers in need of efficient PDF compression capabilities.

Preguntas Frecuentes

¿Cómo puedo comprimir archivos PDF en Python?

Para comprimir archivos PDF en Python, puede usar el método CompressImages de IronPDF. Este método le permite ajustar la calidad de las imágenes para reducir el tamaño del archivo PDF manteniendo una buena calidad. Puede guardar el PDF comprimido usando el método SaveAs.

¿Qué pasos se involucran en la compresión de un documento PDF usando IronPDF?

Primero, instale IronPDF a través de pip y asegúrese de tener instalado el SDK de .NET 6.0. Luego, cargue su PDF usando PdfDocument, aplique el método CompressImages para ajustar la calidad de las imágenes y, finalmente, utilice SaveAs para guardar el PDF comprimido.

¿Cómo instalo IronPDF para Python?

Puede instalar IronPDF para Python usando el comando pip install ironpdf. Asegúrese de tener instalado el SDK de .NET 6.0 ya que IronPDF Python depende de esta versión de la biblioteca .NET.

¿Puedo controlar la intensidad de compresión para los PDFs usando IronPDF?

Sí, puede controlar la intensidad de la compresión en IronPDF ajustando el parámetro entero en el método CompressImages. El parámetro de calidad varía de 1 a 100, con 100 reteniendo la calidad original.

¿Comprimir un PDF con IronPDF afecta la calidad de las imágenes?

Comprimir un PDF con IronPDF puede afectar la calidad de las imágenes, dependiendo de las configuraciones de compresión utilizadas. Usar configuraciones de calidad más bajas reduce el tamaño del archivo pero también puede disminuir la calidad de las imágenes.

¿Qué opciones adicionales ofrece IronPDF para comprimir imágenes en PDFs?

IronPDF ofrece una opción adicional para reducir la resolución de imagen basada en su tamaño visible en el PDF, lo que puede reducir aún más el tamaño del archivo. Sin embargo, esto podría causar distorsión según las configuraciones de imagen.

¿Por qué es importante comprimir archivos PDF?

Comprimir archivos PDF es importante porque reduce su tamaño, facilitando su compartición, carga y almacenamiento. Esto es especialmente útil para documentos grandes que necesitan ser enviados por internet o almacenados eficientemente.

¿Cuáles son los beneficios de usar IronPDF para la compresión de PDF?

IronPDF ofrece una solución robusta para la compresión de PDF, proporcionando control sobre la calidad de las imágenes y el tamaño del archivo. Es rentable, admite funciones adicionales como la rotación de páginas y la conversión de HTML a PDF, y es ideal para desarrolladores que necesitan capacidades completas de manipulación de PDF.

¿Qué opciones de licencia están disponibles para IronPDF?

IronPDF ofrece opciones de licencia asequibles a partir de solo $liteLicense, haciéndolo accesible para desarrolladores que requieren software de PDF de alta calidad sin costos significativos.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más
¿Listo para empezar?
Versión: 2025.9 recién lanzado