如何使用 PDFBOX 将 pdf 拆分为单个 pdf 中的多个页面

How to split a pdf into multiple pages in a single pdf using PDFBOX

要求: 我的 pdf 有 5 页,我需要在单个 pdf 中从第二页开始拆分并在最后一页结束。目前,我已经做到了每页拆分一个 pdf。

当前代码:


public static boolean SepararFC(String sequence, String pathfrom, String pathto) {
     try (PDDocument document = PDDocument.load(new File(pathfrom))) {
        Splitter splitter = new Splitter();
        List<PDDocument> Pages = splitter.split(document);
        for (int i = 0; i < Pages.size(); i++) {
            PDDocument doc = Pages.get(i);
            doc.save(new File(pathfrom, sequence + "_" + i + ".pdf"));
        }
        } catch (IOException e){
            System.err.println(e);
        }
    return true;

假设您的代码是正确的:

public static boolean SepararFC(String sequence, String pathfrom, String pathto) {

    int start = 1;
    int end = 4;
    try (PDDocument document = PDDocument.load(new File(pathfrom))) {
        Splitter splitter = new Splitter();
        List<PDDocument> Pages = splitter.split(document);
        for (int i = 0; i < Pages.size(); i++) {
            PDDocument doc = Pages.get(i);

            if(i > start && i <= end){
                doc.save(new File(pathfrom, sequence + "_" + i + ".pdf"));
            }
        }
        } catch (IOException e){
            System.err.println(e);
        }
return true;

由于您不需要第 1 页,您可以将其删除并保存一个新文件

 try (PDDocument document = PDDocument.load(new File(pathfrom))) {

  //Listing the number of existing pages
  int noOfPages= document.getNumberOfPages();
  System.out.print(noOfPages);

  //Removing the pages
  document.removePage(0);

  System.out.println("page removed");

  //Saving the document
  document.save(new File(pathfrom, sequence + "new"+ ".pdf"));

  //Closing the document
  document.close();} 
catch (IOException e){
  System.err.println(e);
}