DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

carlwils
carlwils

Posted on • Updated on

Compress High-resolution Images in PDF in Java

Usually, a PDF file can contain both text and images and it is these images that can often increase the file size. As a result, the upload and transfer of the large size PDF file may be affected. In this article, you will learn how to programmatically compress the high-resolution images in a PDF file to reduce its file size. Images in low-resolution will not be compressed anymore.

Installation

To complete this task in Java, you'll need to use the Free Spire.PDF for Java API. Below are 2 methods to import the Jar dependency of the free API into your Java application.
Method 1: Download the free API and unzip it. Then add the Spire.Pdf.jar file to your project as dependency.

Method 2: Directly add the jar dependency to maven project by adding the following configurations to the pom.xml.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.pdf.free</artifactId>
        <version>5.1.0</version>
    </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

Sample Code

The PdfPageBase.tryCompressImage(int imgIndex) method offered by Free Spire.PDF for Java allows to compress high-resolution images in a PDF file. The complete sample code is ahown ad below:

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.exporting.PdfImageInfo;

public class CompressImage {
    public static void main(String[] args) {

        //Load the sample PDF document
        PdfDocument doc = new PdfDocument("C:\\Users\\Administrator\\Desktop\\sample.pdf");

        //Set IncrementalUpdate to false
        doc.getFileInfo().setIncrementalUpdate(false);

        //Declare a PdfPageBase variable
        PdfPageBase page;

        //Loop through the pages 
        for (int i = 0; i < doc.getPages().getCount(); i++) {

            //Get the specific page
            page = doc.getPages().get(i);
            if (page != null) {

                if(page.getImagesInfo() != null){

                    //Loop through the images in the page
                    for (PdfImageInfo info: page.getImagesInfo()) {

                        //Use tryCompressImage method the compress high-resolution images
                        page.tryCompressImage(info.getIndex());
                    }
                }
            }
        }

        //Save to file
        doc.saveToFile("Compressed.pdf");
    }
}
Enter fullscreen mode Exit fullscreen mode

CompressImage

Top comments (0)

🌚 Life is too short to browse without dark mode