简体   繁体   中英

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;

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

Assuming your code is correct:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM