Compress High-resolution Images in PDF in Java

This article demonstrates how to compress high-resolution images of a PDF document using Spire.PDF for Java. Images in low-resolution will not be compressed anymore.

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\\Images.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("output/Compressed.pdf");
    }
}

Compress High-resolution Images in PDF in Java