How to reorder the pages of a PDF file?

I am generating Table of Contents after creating a document and I want to move Table of Contents to the start of the document. Suppose that I have 16 pages in my PDF and that the TOC starts from page 13 and ends on page 15. I want to move the TOC to the second page, so that the first page remains page 1 and the last page remains page 16. This code doesn't give me what I want:


public void changePagesOrder() {
    try {
        PdfReader sourcePDFReader = new PdfReader(RESULT1);
        int n = sourcePDFReader.getNumberOfPages();
        System.out.println("no of pages in pdf files..."+n);
        int totalNoPages=n;
        int tocStartsPage=13;
        sourcePDFReader.selectPages(String.format("%d-%d, 2-%d",
            tocStartsPage, totalNoPages-1, tocStartsPage -2));
        PdfStamper stamper = new PdfStamper(sourcePDFReader,
            new FileOutputStream(RESULT2));
    catch(Exception ex) { }
Posted on StackOverflow on Jun 18, 2015 by Surya Rawat

Your code puts your TOC at page 1. That is not what you want according to your description.

Please have a look at the ReorderPages example. There is no selectPages() method in iText 7, that is why we use copyPagesTo() method, so that the pages are now in this order: page 1, page 13, page 14, page 15, page 2, page 3, page 4, page 5, page 6, page 7, page 8, page 9, page 10, page 11, page 12, page 16.

To learn more see the answer to the "How to reorder pages in an existing PDF file" question.

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

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