按标题批量分割PDF文件为多个小PDF文件 代码示例

  1. POM依赖
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>2.0.4</version>
        </dependency>
  1. 代码

import org.apache.pdfbox.io.RandomAccessBuffer;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.apache.pdfbox.multipdf.Splitter;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
import org.apache.pdfbox.pdmodel.interactive.action.PDActionGoTo;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.destination.PDPageDestination;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDDocumentOutline;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineNode;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class PDFUtil {
    private static File file;
    private static String savePath;
    private static int lastPage = 1;
    private static String lastPageName = "start";

    public static void main(String[] args) {
        try {
            startCut("E:\\9800 告警-21.1.pdf","E:\\test\\");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void startCut(String filePath,String savePath) throws Exception {
        PDFUtil.file = new File(filePath);
        PDFUtil.savePath = savePath;
        FileInputStream fis = new FileInputStream(file);
        RandomAccessBuffer randomAccessBuffer = new RandomAccessBuffer(fis);
        PDFParser parser = new PDFParser(randomAccessBuffer);
        parser.parse();
        PDDocument doc = parser.getPDDocument();
        PDDocumentCatalog catalog = doc.getDocumentCatalog();
        PDDocumentOutline outline = catalog.getDocumentOutline();
        PDFUtil util = new PDFUtil();
        if (outline != null) {
            util.printBookmarks(outline, "");
        }
    }
    private void printBookmarks(PDOutlineNode bookmark, String indentation) throws IOException {
        PDOutlineItem current = bookmark.getFirstChild();
        while (current != null) {
            int pages = 0;
            if (current.getDestination() instanceof PDPageDestination) {
                PDPageDestination pd = (PDPageDestination) current.getDestination();
                pages = pd.retrievePageNumber() + 1;
            }
            if (current.getAction() instanceof PDActionGoTo) {
                PDActionGoTo gta = (PDActionGoTo) current.getAction();
                if (gta.getDestination() instanceof PDPageDestination) {
                    PDPageDestination pd = (PDPageDestination) gta.getDestination();
                    pages = pd.retrievePageNumber() + 1;
                }
            }

            String title = current.getTitle();
            String[] s = title.split(" ");
            String name = s[1];
            String save = savePath + lastPageName + ".pdf";
            List<String> fileList = PDFUtil.partitionPdfFile(file.getAbsolutePath(), save, lastPage, pages - 1);
            if (!CollectionUtils.isEmpty(fileList)) {
                PDFUtil.mergePdfFile(fileList, save);
                for (String s1 : fileList) {
                    File file1 = new File(s1);
                    file1.delete();
                }
            }

            if (pages == 0) {
                System.out.println(indentation + current.getTitle());
            } else {
                System.out.println(indentation + current.getTitle() + "  " + pages);
            }
            lastPage = pages;
            lastPageName = name;
            printBookmarks(current, indentation + "    ");
            current = current.getNextSibling();
        }
    }

    /**
     * 对pdf文件按照指定页码进行文件的拆分,每一页拆分成一个新的pdf文件
     *
     * @param pdfFile 原Pdf文件全路径
     * @param newFile 拆分后的文件全路径(文件保存路径和文件名称)
     *                传入null或者空的话,将使用原文件路径和原文件名。
     * @param from    从第几页开始拆分 传入0或负数,将从第一页开始拆分
     * @param end     从第几页结束拆分 传入0或负数,将拆分之文档最后一页
     * @return true(文件合并成功)、false(文件合并失败)
     */
    public static List<String> partitionPdfFile(String pdfFile, String newFile, int from, int end) {
        if (Objects.isNull(pdfFile)) {
            throw new RuntimeException("pdfFile 不能为空");
        }
        if (!pdfFile.endsWith(".pdf") && !pdfFile.endsWith(".PDF")) {
            throw new RuntimeException("pdfFile 必须为pdf文件");
        }
        if (Objects.nonNull(newFile) && !newFile.endsWith(".pdf") && !newFile.endsWith(".PDF")) {
            throw new RuntimeException("newFile 必须为pdf文件");
        }
        File file = new File(pdfFile);
        PDDocument document = null;
        try {
            document = PDDocument.load(file);
            Splitter splitter = new Splitter();
            List<PDDocument> pages = splitter.split(document);
            //处理新传入的文件名称
            newFile = Objects.isNull(newFile) ? pdfFile : newFile;
            if (end > 0 && from > end) {
                throw new RuntimeException("参数from、end均为正整数时,from不能大于end");
            }
            //去除新文件名中的后缀
            int suffixIndex = 0;
            if (newFile.endsWith(".pdf")) {
                suffixIndex = newFile.lastIndexOf(".pdf");
            } else if (newFile.endsWith(".PDF")) {
                suffixIndex = newFile.lastIndexOf(".PDF");
            }
            if (suffixIndex > 0) {
                newFile = newFile.substring(0, suffixIndex);
            }
            if (newFile.lastIndexOf("\\") == -1 || !new File(newFile.substring(0, newFile.lastIndexOf("\\"))).isDirectory()) {
                throw new RuntimeException("参数newFile:" + newFile + ",格式不正确");
            }
            //根据传入的参数对文件列表进行筛选
            from = from <= 0 || from > pages.size() ? 0 : from - 1;
            end = end <= 0 || end > pages.size() ? pages.size() : end;
            pages = pages.subList(from, end);
            //对拆分后的文件进行命名、保存
            List<String> name = new ArrayList<>();
            for (int i = 0; i < pages.size(); i++) {
                PDDocument pd = pages.get(i);
                String fileName = newFile + "-" + (i + 1) + ".pdf";
                pd.save(fileName);
                name.add(fileName);
                pd.close();
            }
            return name;
        } catch (Exception ignored) {
        } finally {
            try {
                if (null != document) document.close();
            } catch (IOException ignored) {
            }
        }
        return null;
    }

    /**
     * 将多个pdf文档合并为一个新的pdf文档
     *
     * @param pdfFiles 要进行合并的pdf文件数组
     * @param newFile  合并后的文件全路径
     * @return true(文件合并成功)、false(文件合并失败)
     */
    public static boolean mergePdfFile(List<String> pdfFiles, String newFile) {
        List<File> files = new ArrayList<>();
        if (Objects.isNull(pdfFiles)) {
            throw new RuntimeException("pdfFiles 不能为空");
        }
        if (Objects.isNull(newFile)) {
            throw new RuntimeException("newFile 不能为空");
        } else if (!newFile.endsWith(".pdf") && !newFile.endsWith(".PDF")) {
            throw new RuntimeException("newFile 必须为pdf文件");
        }
        try {
            for (int i = 0; i < pdfFiles.size(); i++) {
                if (!pdfFiles.get(i).endsWith(".pdf") && !pdfFiles.get(i).endsWith(".PDF")) {
                    throw new RuntimeException(pdfFiles.get(i) + ",文件格式不是pdf");
                }
                File f = new File(pdfFiles.get(i));
                if (!f.exists()) {
                    throw new RuntimeException(f.getPath() + ",不存在");
                }
                files.add(f);
            }
            //Instantiating PDFMergerUtility class
            PDFMergerUtility PDFmerger = new PDFMergerUtility();
            //Setting the destination file
            PDFmerger.setDestinationFileName(newFile);
            //adding the source files
            for (File file : files) {
                PDFmerger.addSource(file);
            }
            //合并pdf
            PDFmerger.mergeDocuments();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

}

pdfbox JAR包

链接:https://pan.baidu.com/s/1NwY2Hgif5ylFTu68TpGkWg 
提取码:t2sc 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
图片批量裁剪器(精华版)是 一款功能丰富、实用、应有尽有的图片/视频批量裁剪、水印、转换、更名,以及其他处理的专业工具!批量处理时不低于5万个文件。 以管理员身份和兼容xp3模式下运行,可支持win7,win8,win10,64位。 图片批量裁剪器(精华版)功能 1. 支持常见图片类型如bmp,jpg,tif,gif,png,支持部分非常见图片类型,如PSD,PCX,ICO,Pdf,动态Gif等等;支持对大多数常见的音频/视频文件格式的裁剪、转换、水印、分割、合并等; 2.提供对图片文件的丰富多彩实用的各种批量裁剪模式,如相对、绝对、固定、大小、等分/非等分分切、分隔、同比/非同比缩放、拼接/无缝拼合、贴边等等几百种裁剪处理功能; 支持圆角矩形/椭圆形/圆形/任意角度裁剪,支持自定义圆角矩形半径裁剪; 3.其他更丰富的裁剪功能,请参见主页说明或程序,比如:提取图片上的文字并保存先裁剪后加水印一步到位忽略处理过的文件夹手动指定裁剪区域多裁剪区域裁剪打印二维码图片转Pdf 过滤小图或缩略图 AB文件夹配对拼合 …… 内置其他功能列表: 1.图片烙制水印(文字水印,图片水印,淘宝卖家专用水印,以及其他上百种水印功能模式供选择,特别如以拍摄日期作为文字水印,递增数字水印等等,批量制卡证等) 2.图片旋转及格式转换(特别功能如智能扳正) 3.图片亮度/对比度调整 4.图片压缩(特色功能如保留Exif信息的压缩) 5.定制图片大小/尺寸(特色功能如能按指定的文件大小压缩,比如压缩到120kb左右,仅压缩大图,小图忽略压缩等) 6.图片像素筛查(从海量图片中筛查出满足条件的图片供删除、移动、复制、更名等) 7.(图片)文件时间属性修改(比如更改拍摄日期,没有做不到只有想不到) 8.图像综合处理 9.(图片)文件批量更名(强大丰富的多种文件批量更名功能) 10.文件随机/顺序/定时抽取分发(将海量文件复制或移动到指定的文件夹中) 11.证件照批量更换背景颜色 12.色块/色条魔术棒裁剪,颜色替换 13.音视频裁剪/分割/合并/转换/加水印/录音/录像 14.批量替换图片中的图片或文字 15.图像批量组合排版 16.证件制作排版(广告公司实用) 17.Jpg图片Exif信息编辑器 18.重复或相似图片批量查找 19.相对/绝对/固定裁剪简易兼容备用版 20.Jpg转视频avi或其他(影楼后期制作DV工具) 21.图片批量浏览挑拣器(影楼客户自选照片实用) 22.图片批量叠加/混合 23.视频批量加密(特色功能如用户可自行在线找回播放密码,一机一码,一视频一码) 24.账号、密码批量管理小秘书(管理你各种账号密码,完全安全加密) 25.动态Gif图片裁剪、水印;图片压制成动态Gif(按时间轴裁剪,裁剪后的gif仍然是动画模式) 26.音频片段截取助手 27.广告喷绘大图专用分切器(喷绘行业专用) 图片批量水印裁剪器 v6.0.20161008精华版更新内容: 1.新增动态Gif水印区域批量涂抹模糊,或者图片水印区域批量涂抹功能; 2.修正水印添加模块中,还原或重设DPI功能时失效异常的问题; 3.在水印批量添加模块中,新增还原原图DPI以及转为CMYK印刷颜色模式的新功能; 4.新增批量生成二维码图片的功能; 5.新增图片裁剪/缩放/格式转换/添加水印等单张综合处理功能模块; 6.修正先选择后裁剪功能实现的问题; 7.新增批量对动态Gif文件指定水印区域模糊化处理功能; 8.新增定时对指定的目录中的图片挂机无人值守自动裁剪功能,忽略已处理过的图片文件; 9.新增纯文字水印添加功能模块; 10.新增学生证件照排版和学生胸卡排版制作打印功能模块; 11.改进修正Jpg系列图片转视频功能,并新增同时给转换后的视频叠加音频的功能; 12.修正改进动态Gif裁剪、水印功能模块; 13.改进跟图片OCR文字识别的有关问题和功能; 14.新增备用下载服务器和网络登录版; 15.修正精确去片头片尾功能; 16.修正某些音频视频文件播放时间不足一秒时无法加载入文件列表的异常; 17.修正媒体批量合并功能模块全部失效的问题; 18.新增以文件夹名作为动态文字水印的功能。 图片批量裁剪器(精华版)截图

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值