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 to reduce its file size. Images in low-resolution will not be compressed anymore.
Tools Used:
● Free Spire.PDF for Java library
● IntelliJ IDEA
Installation
Method 1: Download the free library 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>http://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>
Sample Code
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");
}
}