How to reorder pages in an existing PDF file?

I am using the iText pdf library. Does any one know how I can move pages in an existing PDF? Actually I want to move a couple of the last pages to the start of the document. It is done more or less

I am using the iText pdf library. Does any one know how I can move pages in an existing PDF? Actually I want to move a couple of the last pages to the start of the document.

It is done more or less using the following code, but I don't understand how it works.

reader = new PdfReader(baos.toByteArray());
n = reader.getNumberOfPages();
reader.selectPages(String.format("%d, 1-%d", n, n-1));
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(filename));
stamper.close();
Can any one explain this code in detail?

Posted on StackOverflow on Feb 6, 2014 by Butani Vijay

The selectPages() method doesn’t exist in iText 7 anymore. We use copyPagesTo() with the list of integers as the first argument to reorder pages. This list can consist of increasing page numbers, 1, 2, 3, 4,... If you change the order, for instance: 1, 3, 2, 4,... PdfDocument will serve the pages in that changed order.

Look at the ReorderPages example to see how it works:

PdfDocument srcDoc = new PdfDocument(new PdfReader(src));
PdfDocument resultDoc = new PdfDocument(new PdfWriter(dest));
resultDoc.initializeOutlines();
List pages = new ArrayList();
pages.add(1);
for (int i = 13; i 

Check the resulting PDF to make sure the order is 1, 13, 14, 15, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 16 now.

Click this link if you want to see how to answer this question in iText 5.


Share this article

Ready to use iText?

Try our iText 7 Library and add-ons FREE for 30 days. Test your proof of concept, and see if our solution is right for you.

Get my FREE trial
Contact

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now