Cómo Comprimir Archivos PDF en Java | IronPDF

How to Compress PDF Files in Java

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

PDF documents are commonly used for storing and sharing information, but they can often be quite large in file size. This can be a problem when trying to share or upload PDF documents, as well as for storage. To address this issue, it is possible to compress and save PDF files using IronPDF, a Java PDF Library. Compressing a PDF document reduces its size by removing unnecessary elements or objects, such as embedded fonts and images.

In this article, we will explore the IronPDF library to compress PDF files in Java. We will also provide a code sample to help you understand the import process and implement it in your own projects.

IronPDF: PDF Library

IronPDF is a powerful Java PDF library that offers users the ability to create/generate, manipulate, compress, download, and read PDF files from any language or programming environment. It's capable of creating highly accurate documents with features like document control, form filling, image embedding, compression, and more.

What sets IronPDF apart is its ability to compress existing PDFs, enabling users to significantly reduce their file size while retaining the highest quality output. This makes it perfect for large documents that need to be shared quickly over the internet or through email without sacrificing file quality.

Compress PDF Documents Using IronPDF

Follow the next steps to compress the PDF file size.

Install IronPDF in Java Maven Project

  • To install IronPDF in a Maven project, you will need to add the IronPDF Maven repository and dependency to your project's pom.xml file.

  • Next, add the IronPDF dependency by adding the following to the section of your pom.xml file:

    <dependency>
        <groupId>com.ironsoftware</groupId>
        <artifactId>ironpdf</artifactId>
        <version>your_version_here</version>
    </dependency>
    <dependency>
        <groupId>com.ironsoftware</groupId>
        <artifactId>ironpdf</artifactId>
        <version>your_version_here</version>
    </dependency>
    XML
  • Save your pom.xml file and run MVN install to install the IronPDF dependency.

Once you have completed these steps, you should be able to import and use the IronPDF classes in your project.

Compress PDF File

This code is a Java program that uses the IronPDF library to compress a PDF document.

import com.ironsoftware.ironpdf.*;
import java.io.IOException;
import java.nio.file.Paths;

public class App {
    // Main method to compress PDF
    public static void main(String[] args) throws IOException {
        // Define the path of the source PDF file
        String src = "C:\\Image based PDF.pdf";

        // Load the PDF document from the specified file path
        PdfDocument pdf = PdfDocument.fromFile(Paths.get(src));

        // Compress images within the PDF to 60% of their original quality
        pdf.compressImages(60);

        // Save the compressed PDF to a new destination
        pdf.saveAs(Paths.get("assets/document_compressed.pdf"));

        // Compress images to 90% with additional resolution scaling
        // This can potentially reduce file size further by scaling image resolution
        pdf.compressImages(90, true);

        // Define the path where the final compressed PDF will be saved
        String dest = "C:\\Compressed.pdf";

        // Save the final compressed PDF
        pdf.saveAs(Paths.get(dest));
    }
}
import com.ironsoftware.ironpdf.*;
import java.io.IOException;
import java.nio.file.Paths;

public class App {
    // Main method to compress PDF
    public static void main(String[] args) throws IOException {
        // Define the path of the source PDF file
        String src = "C:\\Image based PDF.pdf";

        // Load the PDF document from the specified file path
        PdfDocument pdf = PdfDocument.fromFile(Paths.get(src));

        // Compress images within the PDF to 60% of their original quality
        pdf.compressImages(60);

        // Save the compressed PDF to a new destination
        pdf.saveAs(Paths.get("assets/document_compressed.pdf"));

        // Compress images to 90% with additional resolution scaling
        // This can potentially reduce file size further by scaling image resolution
        pdf.compressImages(90, true);

        // Define the path where the final compressed PDF will be saved
        String dest = "C:\\Compressed.pdf";

        // Save the final compressed PDF
        pdf.saveAs(Paths.get(dest));
    }
}
JAVA

The code imports the IronPDF library and the necessary Java classes for file handling. The main method of the App class reads a PDF document called "Image based PDF.pdf" from the "C:" directory, compresses the images in the PDF by 60%, and saves the new compressed version as "document_compressed.pdf" in the "assets" directory.

Then, it compresses the images in the PDF by 90% and saves the resulting PDF file as "Compressed.pdf" in the "C:" directory. The second optional parameter can scale down the image resolution according to its visible size in the PDF document, which might lead to image distortion with some configurations.

You can see the comparison between the compressed file and the original PDF file.

Before Compression

Original PDF

After Compression

Compressed PDF Output

Conclusion

IronPDF is a powerful yet affordable tool for compressing PDF size in Java with many features like page rotation, HTML to PDF conversion, and image manipulation. These features make IronPDF a great choice when looking for low-cost solutions to compress PDFs while still getting the added benefits of the comprehensive library.

License pricing and options start from just $799, which offers budget-conscious developers an opportunity to access high-quality software without having to pay large amounts. All things considered, IronPDF provides an excellent choice for developers looking for reliable and robust PDF optimization with no hassle.

Preguntas Frecuentes

¿Cómo puedo comprimir archivos PDF en Java?

Puedes comprimir archivos PDF en Java utilizando IronPDF cargando el documento PDF, comprimiendo las imágenes dentro del PDF y luego guardando el PDF comprimido en una ubicación deseada. Este proceso asegura que el tamaño del archivo se reduzca mientras se mantiene la calidad.

¿Qué pasos están involucrados en la configuración de IronPDF en un proyecto Maven de Java?

Para configurar IronPDF en un proyecto Maven de Java, necesitas agregar el repositorio Maven de IronPDF y la dependencia en el archivo pom.xml de tu proyecto. Después de guardar el archivo, ejecuta mvn install para instalar la dependencia de IronPDF.

¿Puedo reducir el tamaño de archivo de un PDF sin perder calidad utilizando una biblioteca Java?

Sí, IronPDF te permite reducir eficientemente el tamaño de los archivos PDF sin perder calidad al comprimir imágenes y optimizar el contenido del documento. Esto lo hace ideal para compartir y almacenar documentos grandes.

¿Qué características adicionales ofrece IronPDF además de la compresión de PDF?

Además de la compresión de PDF, IronPDF proporciona características como rotación de páginas, conversión de HTML a PDF y manipulación de imágenes, ofreciendo una solución integral para las distintas necesidades de optimización de PDF.

¿Cómo asegura IronPDF una alta calidad de salida al comprimir PDFs?

IronPDF mantiene una alta calidad de salida al comprimir selectivamente las imágenes y optimizar recursos dentro del PDF, asegurando que la reducción del tamaño de archivo no comprometa la calidad del documento.

¿Es posible ajustar la resolución de las imágenes en los PDFs usando IronPDF?

Sí, con IronPDF, puedes ajustar la resolución de la imagen según su tamaño visible dentro del PDF, lo que puede ayudar a reducir el tamaño de archivo aún más, aunque puede afectar la claridad de la imagen si se reduce demasiado.

¿Cuáles son las ventajas de usar IronPDF para la compresión de PDF en Java?

Usar IronPDF para la compresión de PDF en Java ofrece ventajas como una significativa reducción del tamaño de archivo, preservación de la calidad del documento y características adicionales como conversión de HTML a PDF, convirtiéndolo en una herramienta versátil y rentable.

¿Cómo compara visualmente IronPDF los PDFs originales y comprimidos?

IronPDF proporciona comparaciones visuales entre los PDFs originales y comprimidos, demostrando la efectividad del proceso de compresión y asegurando que la calidad se mantenga alta a pesar de la reducción del tamaño de archivo.

Darrius Serrant
Ingeniero de Software Full Stack (WebOps)

Darrius Serrant tiene una licenciatura en Ciencias de la Computación de la Universidad de Miami y trabaja como Ingeniero de Marketing WebOps Full Stack en Iron Software. Atraído por la programación desde joven, vio la computación como algo misterioso y accesible, convirtiéndolo en el ...

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