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, newFileOutputStream(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:
protected void manipulatePdf(String dest) throws Exception {
PdfDocument srcDoc = new PdfDocument(new PdfReader(new RandomAccessSourceFactory()
.createSource(createBaos().toByteArray()), new ReaderProperties()));
PdfDocument resultDoc = new PdfDocument(new PdfWriter(dest));
// One should call this method to preserve the outlines of the source pdf file, otherwise they
// will be absent in the resultant document to which we copy pages. In this particular sample,
// however, this line doesn't make sense, since the source pdf lacks outlines
resultDoc.initializeOutlines();
List < Integer > pages = new ArrayList < > ();
pages.add(1);
for (int i = 13; i <= 15; i++) {
pages.add(i);
}
for (int i = 2; i <= 12; i++) {
pages.add(i);
}
pages.add(16);
srcDoc.copyPagesTo(pages, resultDoc);
resultDoc.close();
srcDoc.close();
}
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? | iText 5 PDF Development Guide if you want to see how to answer this question in iText 5.