You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PDFBox生成PDF体积大于iText,Java中PDFBox有压缩方案吗?

PDFBox缩小PDF体积的压缩方法

针对PDFBox生成的PDF体积过大的问题,以下是几种有效的压缩手段:

  • 压缩文档中的图像
    PDF里的图像往往是体积大头,PDFBox支持对图像进行重采样、格式转换来压缩:

    PDDocument document = PDDocument.load(new File("large.pdf"));
    PDPageTree pages = document.getPages();
    for (PDPage page : pages) {
        PDResources resources = page.getResources();
        for (COSName name : resources.getXObjectNames()) {
            PDXObject xobject = resources.getXObject(name);
            if (xobject instanceof PDImageXObject) {
                PDImageXObject image = (PDImageXObject) xobject;
                // 重采样为低分辨率,比如按比例缩小
                BufferedImage bufferedImage = image.getImage();
                BufferedImage resizedImage = new BufferedImage(
                    (int)(bufferedImage.getWidth() * 0.5),
                    (int)(bufferedImage.getHeight() * 0.5),
                    bufferedImage.getType()
                );
                Graphics2D g = resizedImage.createGraphics();
                g.drawImage(bufferedImage, 0, 0, resizedImage.getWidth(), resizedImage.getHeight(), null);
                g.dispose();
                // 替换原图像为压缩后的JPEG格式
                PDImageXObject compressedImage = PDImageXObject.createFromByteArray(
                    document,
                    ImageIOUtilities.imageToByteArray(resizedImage, "JPEG"),
                    "compressed"
                );
                resources.putXObject(name, compressedImage);
            }
        }
    }
    document.save("compressed.pdf");
    document.close();
    
  • 启用内容流压缩
    PDFBox默认可能未开启全量内容流压缩,保存文档时可指定参数强制压缩页面内容流、字体等对象:

    PDDocument document = PDDocument.load(new File("large.pdf"));
    // 创建保存选项并启用压缩
    SaveOptions options = SaveOptions.createSaveOptions(SaveFormat.PDF);
    options.setCompressContentStreams(true);
    options.setCompressImages(true);
    document.save("compressed.pdf", options);
    document.close();
    
  • 移除冗余对象
    清理文档中未使用的字体、图像、注释或元数据,减少无用数据占用:

    PDDocument document = PDDocument.load(new File("large.pdf"));
    // 使用PDFCleaner清理冗余资源
    PDFCleaner.cleanUp(document);
    // 手动清理页面未使用资源
    PDPageTree pages = document.getPages();
    for (PDPage page : pages) {
        page.getResources().cleanUp();
    }
    document.save("cleaned.pdf");
    document.close();
    
  • 字体子集化
    如果生成PDF时嵌入了完整字体,改为仅嵌入文档中实际用到的字符子集,可大幅降低字体体积:

    PDType0Font font = PDType0Font.load(document, new File("font.ttf"), true);
    // 第二个参数设为true即启用子集化
    

内容的提问来源于stack exchange,提问作者rohit Chougule

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 08:31:07