Search code examples
javapdfbox

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


Requirement: My pdf has 5 pages, I need to start the split on the second page and end at the last page, in a single pdf. Currently, I have made it so that it splits one pdf per page.

Current code:


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;


Solution

  • Since you don't want page 1, you can just remove it and save a new file

     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);
    }