java压缩pdf体积,图片体积

pdf整体进行压缩,图片进行压缩

        // 生成主证书的PDF路径  创建一个文件
        String pdfPath = UploadDown.createFile(".pdf");
          outputStream = new FileOutputStream(pdfPath);
             bufferedOutputStream = new BufferedOutputStream(outputStream);
            writer = PdfWriter.getInstance(document, bufferedOutputStream);
            writer.setCompressionLevel(compressionLevel); // 压缩9
            writer.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

是图片的格式对不上

添加下面的依赖试试:

     
        
            com.twelvemonkeys.imageio
            imageio-jpeg
            3.3
        
        
            com.twelvemonkeys.imageio
            imageio-tiff
            3.3
        

你可能感兴趣的:(java,pdf,开发语言)