pdf整体进行压缩,图片进行压缩
// 生成主证书的PDF路径 创建一个文件String pdfPath = UploadDown.createFile(".pdf");outputStream = new FileOutputStream(pdfPath);bufferedOutputStream = new BufferedOutputStream(outputStream);writer = PdfWriter.getInstance(document, bufferedOutputStream);writer.setCompressionLevel(compressionLevel); // 压缩9writer.setFullCompression(); // 全面压缩
发现压缩力度不大,主要还是要对pdf中的图片进行压缩,我这里压缩图片的精度设置成2,具体根据你的业务逻辑来,
public static Image optimizeImage(String source) {// 这个自己调,如果图片过大,可以调小这个数字double quality = 0.2;try {ByteArrayOutputStream os = new ByteArrayOutputStream();System.out.println("压缩图片路径:"+source);if (source.startsWith("http://") || source.startsWith("https://") || source.startsWith("ftp://")) {Thumbnails.of(new URL(source)).scale(1).outputQuality(quality).toOutputStream(os);} else {Thumbnails.of(source).scale(1).outputQuality(quality).toOutputStream(os);}byte[] bytes = os.toByteArray();// 压缩后的图片用流接收Image image = Image.getInstance(bytes);return image;} catch (Exception e) {log.error("压缩图片失败", e);e.printStackTrace();throw new MyException("压缩图片失败"+e.getMessage());}}
压缩图片报错的话:
报错信息:javax.imageio.IIOException: Unsupported Image Type
是图片的格式对不上
添加下面的依赖试试:
<!-- cmyk格式图片转换 --><dependency><groupId>com.twelvemonkeys.imageio</groupId><artifactId>imageio-jpeg</artifactId><version>3.3</version></dependency><dependency><groupId>com.twelvemonkeys.imageio</groupId><artifactId>imageio-tiff</artifactId><version>3.3</version></dependency>