当遇到上传PDF文件大小有限制的场景时,可以使用Apache PDFBox压缩PDF文件。

  • 依赖
<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>pdfbox</artifactId>
    <version>2.0.28</version>
</dependency>
  • 压缩代码
public static void compressPdfWithImageQuality(String inputPath, String outputPath, float imageQuality) throws IOException {

	try (PDDocument document = PDDocument.load(new File(inputPath))) {
		// 设置是否移除安全设置
		document.setAllSecurityToBeRemoved(true);
		// 迭代处理每一页
		for (PDPage page : document.getPages()) {
			PDResources resources = page.getResources();
			// 获取该页所有的XObject资源(通常图像包含在其中)
			Iterable<COSName> xObjectNames = resources.getXObjectNames();
			if (xObjectNames != null) {
				Iterator<COSName> iterator = xObjectNames.iterator();
				while (iterator.hasNext()) {
					COSName name = iterator.next();
					// 检查该对象是否为图像XObject
					if (resources.isImageXObject(name)) {
						PDImageXObject image = (PDImageXObject) resources.getXObject(name);
						// 将PDF中的图像对象转换为BufferedImage
						BufferedImage bufferedImage = image.getImage();
						// 使用JPEG编码重新压缩图像,并指定质量(0-1f); 注意:此操作会将非JPEG图像也转换为JPEG格式
						PDImageXObject compressedImage = JPEGFactory.createFromImage(document, bufferedImage, imageQuality);
						// 用压缩后的图像替换原始图像
						resources.put(name, compressedImage);
					}
				}
			}
		}
		// 保存压缩后的文档
		document.save(outputPath);
	}

}
  • 测试
public static void main(String[] args) throws Exception {
		String inputPath = "E:\\2025\\input.pdf";
		String outPath = "E:\\2025\\out.pdf";
		compressPdfWithImageQuality(inputPath, outPath, 0.8f);
}

原文件6.42MB,要求上传5MB以下的文件,使用上述代码压缩后的大小为4.82MB。