简体   繁体   中英

Splitting one Pdf file to multiple according to the file-size

I have been trying to split one big PDF file to multiple pdf files based on its size. I was able to split it but it only creates one single file and rest of the file data is lost. Means it does not create more than one files to split it. Can anyone please help? Here is my code

public static void main(String[] args) {
    try {
        PdfReader Split_PDF_By_Size = new PdfReader("C:\\Temp_Workspace\\TestZip\\input1.pdf");
        Document document = new Document();
        PdfCopy copy = new PdfCopy(document, new FileOutputStream("C:\\Temp_Workspace\\TestZip\\File1.pdf"));
        document.open();

        int number_of_pages = Split_PDF_By_Size.getNumberOfPages();
        int pagenumber = 1; /* To generate file name dynamically */
        // int Find_PDF_Size; /* To get PDF size in bytes */
        float combinedsize = 0; /* To convert this to Kilobytes and estimate new PDF size */
        for (int i = 1; i < number_of_pages; i++ ) {
            float Find_PDF_Size;
            if (combinedsize == 0 && i != 1) {
                document = new Document();
                pagenumber++;
                String FileName = "File" + pagenumber + ".pdf";
                copy = new PdfCopy(document, new FileOutputStream(FileName));
                document.open();
            }

            copy.addPage(copy.getImportedPage(Split_PDF_By_Size, i));
            Find_PDF_Size = copy.getCurrentDocumentSize();
            combinedsize = (float)Find_PDF_Size / 1024;
            if (combinedsize > 496 || i == number_of_pages) {
                document.close();
                combinedsize = 0;
            }
        }

        System.out.println("PDF Split By Size Completed. Number of Documents Created:" + pagenumber);                        
    }
    catch (Exception i)
    {
        System.out.println(i);
    }
}

}

(BTW, it would have been great if you had tagged your question with itext , too.)

PdfCopy used to close the PdfReaders it imported pages from whenever the source PdfReader for page imports switched or the PdfCopy was closed. This was due to the original intended use case to create one target PDF from multiple source PDFs in combination with the fact that many users forget to close their PdfReaders .

Thus, after you close the first target PdfCopy , the PdfReader is closed, too, and no further pages are extracted.

If I interpret the most recent checkins into the iText SVN repository correctly, this implicit closing of PdfReaders is in the process of being removed from the code. Therefore, with one of the next iText versions, your code may work as intended.

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