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 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));
Can any one explain this code in detail?

Posted on StackOverflow on Feb 6, 2014 by Butani Vijay

The selectPages() method is explained in chapter 6 of "iText in Action - Second Edition" In the context of code snipper 6.3 and 6.11, it is used to reduce the number of pages being read by PdfReader for consumption by PdfStamper or PdfCopy. However, it can also be used to reorder pages. First allow me to explain the syntax.

There are different flavors of the selectPages() method:

You can pass a List containing all the page numbers you want to keep. This list can consist of increasing page numbers, 1, 2, 3, 4,... If you change the order, for instance: 1, 3, 2, 4,... PdfReader will serve the pages in that changed order.

You can also pass a String (which is what is done in your snippet) using the following syntax:


You can have multiple ranges separated by commas, and the ! modifier removes pages from what is already selected. The range changes are incremental; numbers are added or deleted as the range appears. The start or the end can be omitted; if you omit both, you need at least o (odd; selects all odd pages) or e (even; selects all even pages).

In your case, we have:

String.format("%d, 1-%d", n, n-1)

Suppose we have a document with 10 pages, then n equals 10 and the result of the formatting operation is: "10, 1-9". In this case, PdfReader will present the last page as the first one, followed by pages 1 to 9.

Now suppose that you have a TOC that starts on page 8, and you want to move this TOC to the first pages, then you need something like this: 8-10, 1-7, or if toc equals 8 and n equals 10:

String.format("%d-%d, 1-%d", toc, n, toc -1)

For more info about the format() method, see the API docs for String and the Format String syntax.

See also How to reorder the pages of a PDF file?

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

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