1 概述
通常,一个 PDF 文件可以同时包含文本和图像,正是这些图像往往可以增加文件大小。因此,上传和传输的大型 PDF 文件可能会受到影响。在本文中,您将了解如何以编程方式压缩 PDF 文件中的高分辨率图像,以减小其文件大小。低分辨率的图像将不再被压缩。
2 安装依赖库
要在 Java 中完成这项任务,您需要使用 Java API 的 Free Spire.PDF。下面有两种方法可以将免费 API 的 Jar 依赖项导入到 Java 应用程序中。
方法1: 下载免费的 API 并解压缩。然后将 Spire.Pdf.jar 文件作为依赖项添加到项目中。
方法2: 通过向 pom.xml 中添加以下配置,直接向 maven 项目添加 jar 依赖项。(建议选择这种方法)
<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>
代码实现
Free Spire.PDF 为 Java 提供的 PdfPageBase.tryCompressImage (int imgIndex)
方法允许将高分辨率图像压缩到 PDF 文件中。完整的示例代码如下:
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");
}
}