Skip to main content
Skip table of contents

How to reorder pages in an existing PDF file?

I want to move a couple of the last pages to the start of my document.

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 anyone 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 How to reorder pages in an existing PDF file? if you want to see how to answer this question in iText 5.

JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.