Reordering pages

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

31st May 2016
iText PDF

Switch code for this example

ReorderPages.java
  1. /*
  2.  
  3.     This file is part of the iText (R) project.
  4.     Copyright (c) 1998-2016 iText Group NV
  5.  
  6. */
  7.  
  8. /**
  9.  * Example written by Bruno Lowagie in answer to:
  10.  * http://stackoverflow.com/questions/30911216/how-to-re-arrange-pages-in-pdf-using-itext
  11.  */
  12. package com.itextpdf.samples.sandbox.stamper;
  13.  
  14. import com.itextpdf.io.source.RandomAccessSourceFactory;
  15. import com.itextpdf.kernel.pdf.PdfDocument;
  16. import com.itextpdf.kernel.pdf.PdfReader;
  17. import com.itextpdf.kernel.pdf.PdfWriter;
  18. import com.itextpdf.kernel.pdf.ReaderProperties;
  19. import com.itextpdf.layout.Document;
  20. import com.itextpdf.layout.element.AreaBreak;
  21. import com.itextpdf.layout.element.Paragraph;
  22. import com.itextpdf.samples.GenericTest;
  23. import com.itextpdf.test.annotations.type.SampleTest;
  24.  
  25. import org.junit.experimental.categories.Category;
  26.  
  27. import java.io.ByteArrayOutputStream;
  28. import java.io.File;
  29. import java.util.ArrayList;
  30. import java.util.List;
  31.  
  32. @Category(SampleTest.class)
  33. public class ReorderPages extends GenericTest {
  34.     public static final String DEST = "./target/test/resources/sandbox/stamper/reorder_pages.pdf";
  35.  
  36.     public static void main(String[] args) throws Exception {
  37.         File file = new File(DEST);
  38.         file.getParentFile().mkdirs();
  39.         new ReorderPages().manipulatePdf(DEST);
  40.     }
  41.  
  42.     @Override
  43.     protected void manipulatePdf(String dest) throws Exception {
  44.         ByteArrayOutputStream baos = new ByteArrayOutputStream();
  45.         PdfDocument pdfDoc = new PdfDocument(new PdfWriter(baos));
  46.         Document doc = new Document(pdfDoc);
  47.  
  48.         for (int i = 1; i < 17; i++) {
  49.             doc.add(new Paragraph(String.format("Page %s", i)));
  50.             if (16 != i) {
  51.                 doc.add(new AreaBreak());
  52.             }
  53.         }
  54.         doc.close();
  55.  
  56.         PdfDocument srcDoc = new PdfDocument(new PdfReader(new RandomAccessSourceFactory().createSource(baos.toByteArray())
  57.                 , new ReaderProperties()));
  58.         PdfDocument resultDoc = new PdfDocument(new PdfWriter(dest));
  59.         resultDoc.initializeOutlines();
  60.  
  61.         List pages = new ArrayList();
  62.         pages.add(1);
  63.         for (int i = 13; i
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