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)); stamper.close(); } catch(Exception ex) { } }
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 How to reorder the pages of a PDF file? if you want to see how to answer this question in iText 5.