Split PDF by delimiter?

Viewed 278

I have invoices combined in a single pdf file. Some invoices are half a page in size, while some invoices are larger than one page. How can I separate all these invoices as separate files by using static texts at the beginning of each invoice as separators? Or I can use a different method you suggest. Sample file.

1 Answers

You need to extend the Splitter.splitAtPage method to indicate where you want to split your PDF.

Here is a working example:

public class PdfBoxSplitter {
    private static String DELIMITER = "Efactory Inc";

    public static void main(String[] args) throws IOException {
        File file = new File("document.pdf");

        try (PDDocument document = PDDocument.load(file)) {

            // First find the list of pages where we need to split the PDF
            List<Integer> splitPages = new ArrayList<>();
            for (int page = 1; page <= document.getNumberOfPages(); page++) {
                PDFTextStripper pdfStripper = new PDFTextStripper();
                pdfStripper.setStartPage(page);
                pdfStripper.setEndPage(page);
                String parsedText = pdfStripper.getText(document);
                if (parsedText.contains(DELIMITER)) splitPages.add(page - 1);
            }

            // Instantiate the custom splitter 
            Splitter splitter = new Splitter() {
                protected boolean splitAtPage(int pageNumber) {
                    return splitPages.contains(pageNumber);
                }
            };

            // Split the document and save each part
            List<PDDocument> docs = splitter.split(document);
            int cpt = 1;
            for (PDDocument doc : docs) {
                File f = new File("Document" + (cpt++) + ".pdf");
                doc.save(f);
            }
        }
    }
}
Related