分割 PDF 文件

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/RO_wsy/article/details/79231046

分割 PDF 文件

增加依赖

<dependency>
  <groupId>org.apache.pdfbox</groupId>
  <artifactId>pdfbox</artifactId>
  <version>2.0.4</version>
</dependency>

编写代码

package wang.ronnie.pdf;

import org.apache.pdfbox.multipdf.Splitter;
import org.apache.pdfbox.pdmodel.PDDocument;

import java.io.File;
import java.io.IOException;
import java.util.List;

public class PdfSplitter {

    public static void main(String[] args) throws IOException {

        File file = new File("/Users/xxx/Downloads/Psychology and Life(20ed)-Gerrig.pdf");
        PDDocument book = PDDocument.load(file);
        Splitter splitter = new Splitter();
        List<PDDocument> pages = splitter.split(book);

        splitToChapter(pages, 31, 50, "chapter1.pdf");
        splitToChapter(pages, 50, 68, "chapter2.pdf");
        splitToChapter(pages, 68, 76, "statistical_supplement.pdf");
        splitToChapter(pages, 76, 109, "chapter3.pdf");
        splitToChapter(pages, 109, 150, "chapter4.pdf");
        splitToChapter(pages, 150, 174, "chapter5.pdf");
        splitToChapter(pages, 174, 203, "chapter6.pdf");
        splitToChapter(pages, 203, 236, "chapter7.pdf");
        splitToChapter(pages, 236, 269, "chapter8.pdf");
        splitToChapter(pages, 269, 290, "chapter9.pdf");
        splitToChapter(pages, 290, 327, "chapter10.pdf");
        splitToChapter(pages, 327, 352, "chapter11.pdf");
        splitToChapter(pages, 352, 386, "chapter12.pdf");
        splitToChapter(pages, 386, 415, "chapter13.pdf");
        splitToChapter(pages, 415, 448, "chapter14.pdf");
        splitToChapter(pages, 448, 476, "chapter15.pdf");
        splitToChapter(pages, 476, 512, "chapter16.pdf");

        book.close();
    }

    private static void splitToChapter(List<PDDocument> pages, int startPage, int endPage, String chapterName) throws IOException {

        PDDocument chapterPdf = new PDDocument();
        for (int i = startPage; i < endPage; i++) {
            chapterPdf.addPage(pages.get(i).getPage(0));
        }
        chapterPdf.save(new File("/Users/xxx/psychology_and_life/" + chapterName));
        chapterPdf.close();
    }
}

Done

搞定

展开阅读全文

没有更多推荐了,返回首页