Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache PDFBox: Move the last page to first Page

Tags:

java

pdf

apache

I'm writing a simple Java Application with Apache PDFBox. I have a several PDFs where the last page is the index of the content in the previous pages.

I need the index (last page) became the first page of the PDF file.

Is it possible?

I've also discovered the http://itextpdf.com/ library that sound better than Apache PDFBox, but in this case i don't know if i can do the thing i need either

Or maybe i can use this: http://saaspose.com/docs/display/pdf/How+to+Move+Page+within+a+Pdf+Document+%28Java+SDK%29

like image 470
Deviling Master Avatar asked Jan 16 '23 06:01

Deviling Master


2 Answers

With PDFBox you can open the original PDF into a PDDocument, then use getDocumentCatalog().getAllPages() to get a list of of the pages. Rearrange the list in the order you want, and write out each page to the new documents.

        PDDocument newDoc = new PDDocument();
        PDDocument oldDoc = PDDocument.load (args[0]);
        List allPages = oldDoc.getDocumentCatalog().getAllPages();

        // Code to rearrange the list goes here

        for ( int curPageCnt = 0; curPageCnt < allPages.size(); curPageCnt++ )
        {
            newDoc.addPage( ( PDPage )allPages.get ( curPageCnt ) );
        } // end for
like image 83
Pengo Avatar answered Jan 28 '23 23:01

Pengo


I am using PDFBox version 2.0.0. Here is how I move the last page to the first position:

public static PDDocument moveLastPageToFirst(PDDocument documentToRearrangePages) {
    PDPageTree allPages = documentToRearrangePages.getDocumentCatalog().getPages();
    if (allPages.getCount() > 1) {
        PDPage lastPage = allPages.get(allPages.getCount() - 1);
        allPages.remove(allPages.getCount() - 1);
        PDPage firstPage = allPages.get(0);
        allPages.insertBefore(lastPage, firstPage);
    }
    return documentToRearrangePages;
}
like image 27
Bahadir Tasdemir Avatar answered Jan 28 '23 22:01

Bahadir Tasdemir