Reordering pages

This is a code example of iText PDF, discover more.

8th November 2015
admin-marketing

Switch code for this example

ReorderPages.java
  1. /*
  2.  * Example written by Bruno Lowagie in answer to:
  3.  * http://stackoverflow.com/questions/30911216/how-to-re-arrange-pages-in-pdf-using-itext
  4.  */
  5. package sandbox.stamper;
  6.  
  7. import com.itextpdf.text.Document;
  8. import com.itextpdf.text.DocumentException;
  9. import com.itextpdf.text.Paragraph;
  10. import com.itextpdf.text.pdf.PdfReader;
  11. import com.itextpdf.text.pdf.PdfStamper;
  12. import com.itextpdf.text.pdf.PdfWriter;
  13.  
  14. import java.io.ByteArrayOutputStream;
  15. import java.io.File;
  16. import java.io.FileOutputStream;
  17. import java.io.IOException;
  18. import sandbox.WrapToTest;
  19.  
  20. /**
  21.  *
  22.  * @author Bruno Lowagie (iText Software)
  23.  */
  24. @WrapToTest
  25. public class ReorderPages {
  26.     public static final String DEST = "results/stamper/reordered.pdf";
  27.     public static void main(String[] args) throws IOException, DocumentException {
  28.         File file = new File(DEST);
  29.         file.getParentFile().mkdirs();
  30.         new ReorderPages().createPdf(DEST);
  31.     }
  32.    
  33.     public void createPdf(String dest) throws IOException, DocumentException {
  34.         ByteArrayOutputStream baos = new ByteArrayOutputStream();
  35.         Document document = new Document();
  36.         PdfWriter.getInstance(document, baos);
  37.         document.open();
  38.         for (int i = 1; i < 17; i++) {
  39.             document.add(new Paragraph(String.format("Page %s", i)));
  40.             document.newPage();
  41.         }
  42.         document.close();
  43.         PdfReader reader = new PdfReader(baos.toByteArray());
  44.         int startToc = 13;
  45.         int n = reader.getNumberOfPages();
  46.         reader.selectPages(String.format("1,%s-%s, 2-%s, %s", startToc, n-1, startToc - 1, n));
  47.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
  48.         stamper.close();
  49.     }
  50. }
Contact

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