pdfbox按页数拆分PDF文件

工具类————pdfbox

pom.xml引入依赖

 (choose version) 参考 MVN REPOSITORY

        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>3.0.0-RC1</version>
        </dependency>

代码示例

@Service
@Slf4j
public class FileProcessor {

    /**
     * 拆分PDF
     */
    public void splitPdf(String sourcePath) {
        try (PDDocument document = Loader.loadPDF(new File(sourcePath))) {
            if (document.getNumberOfPages() == 0) {
                log.error("不是有效的 PDF 文件");
                return;
            }
            splitDocument(document);
        } catch (IOException e) {
            log.error("拆分PDF文件失败, path = {}", sourcePath, e);
        }
    }

    private void splitDocument(PDDocument document) throws IOException {
        int i = 0;
        for (PDPage page : document.getPages()) {
            try (PDDocument pdDocument = new PDDocument()) {
                pdDocument.addPage(page);
                pdDocument.save(getFilename(i));
            }
            i++;
        }
    }

    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>

 

posted @ 2023-07-26 18:11  Ashe|||^_^  阅读(314)  评论(0)    收藏  举报