Java如何使用Java將PDF分割成多個文件?

2019-10-16 22:28:54

在Java程式設計中,如何使用Java將PDF分割成多個文件?

以下是使用Java將PDF文件頁面分割成多個文件的範例程式。

package com.yiibai;

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

import java.io.File;
import java.io.IOException;

import java.util.List;
import java.util.Iterator;

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

        // Creating PDF document object
        PDDocument document = new PDDocument();

        File file = new File("F:/worksp/javaexamples/java_apache_pdf_box/AddPages.pdf");
        PDDocument.load(file);

        for (int i = 0; i < 10; i++) {
            // Creating a blank page
            PDPage blankPage = new PDPage();
            // Adding the blank page to the document
            document.addPage(blankPage);
        }
        // Saving the document
        document.save("F:/worksp/javaexamples/java_apache_pdf_box/splitpdf_IP.pdf");
        System.out.println("PDF created");

        // Loading an existing PDF document
        File file2 = new File("F:/worksp/javaexamples/java_apache_pdf_box/splitpdf_IP.pdf");
        PDDocument doc = PDDocument.load(file2);

        // Instantiating Splitter class
        Splitter splitter = new Splitter();

        // splitting the pages of a PDF document
        List<PDDocument> Pages = splitter.split(doc);

        // Creating an iterator
        Iterator<PDDocument> iterator = Pages.listIterator();

        // Saving each page as an individual document
        int i = 1;

        while (iterator.hasNext()) {
            PDDocument pd = iterator.next();
            pd.save("F:/worksp/javaexamples/java_apache_pdf_box/splitOP" + i++ + ".pdf");
        }
        System.out.println("PDF splitted");
    }
}

執行上面範例程式碼,得到以下結果 -

PDF created
PDF splitted

此時,程式已經分割成多個PDF檔案,如下所示 -