按页数拆分PDF文件

发布时间 2023-07-26 18:16:52作者: ashet

pom.xml引入依赖

(choose version) 参考 https://mvnrepository.com/

点击查看代码
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>3.0.0-RC1</version>
        </dependency>

代码示例

点击查看代码
    /**
     * 拆分PDF
     */
    public void splitPdf(String sourcePath) {
        Path path = Paths.get(sourcePath);
        try {
            if (!Files.exists(path) || Files.size(path) == 0) {
                log.error("路径: {} 不存在文件", sourcePath);
                return;
            }
            // 根据页数拆分PDF文件
            try (PDDocument document = Loader.loadPDF(new File(sourcePath))) {
                int i = 0;
                for (PDPage page : document.getPages()) {
                    try (PDDocument pdDocument = new PDDocument()) {
                        pdDocument.addPage(page);
                        pdDocument.save(getFilename(i));
                    }
                    i++;
                }
            }
        } catch (IOException e) {
            log.error("拆分PDF文件失败, path = {}", sourcePath, e);
        }
    }

    private String getFilename(int i) {
        return String.format("C:\\Users\\Administrator\\Downloads\\_%s.pdf", i);
    }

3.0.0-beta1版本在使用中,拆分的第一页PDF文件为空白内容,请勿使用该版本,当前测试时间2023年7月26日

点击查看代码
<!-- https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox -->
<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>pdfbox</artifactId>
    <version>3.0.0-beta1</version>
</dependency>