Splitting a PDF file

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

7th November 2015
admin-marketing

Switch code for this example

MergeAndCount.java
  1. /**
  2.  * Example written by Bruno Lowagie.
  3.  * This example will only work with iText 5.5.6 and higher (you also need the xtra package).
  4.  */
  5. package sandbox.merge;
  6.  
  7. import com.itextpdf.text.DocumentException;
  8. import com.itextpdf.text.log.LoggerFactory;
  9. import com.itextpdf.text.log.SysoLogger;
  10. import com.itextpdf.text.pdf.PdfReader;
  11. import com.itextpdf.text.pdf.util.SmartPdfSplitter;
  12. import java.io.File;
  13.  
  14. import java.io.FileOutputStream;
  15. import java.io.IOException;
  16.  
  17. public class MergeAndCount {
  18.  
  19.     /** The original PDF file. */
  20.     public static final String SRC
  21.         = "resources/pdfs/Wrong.pdf";
  22.  
  23.     /** The resulting PDF file. */
  24.     public static final String DEST
  25.         = "results/merge/pages_counted.pdf";
  26.    
  27.     /**
  28.      * Manipulates a PDF file src with the file dest as result
  29.      * @param src the original PDF
  30.      * @param dest the resulting PDF
  31.      * @throws IOException
  32.      * @throws DocumentException
  33.      */
  34.     public void manipulatePdf(String src, String dest)
  35.         throws IOException, DocumentException {
  36.         PdfReader reader = new PdfReader(src);
  37.         SmartPdfSplitter splitter = new SmartPdfSplitter(reader);
  38.         int part = 1;
  39.         while (splitter.hasMorePages()) {
  40.             splitter.split(new FileOutputStream("results/merge/part_" + part + ".pdf"), 200000);
  41.             part++;
  42.         }
  43.         reader.close();
  44.     }
  45.  
  46.     /**
  47.      * Main method.
  48.      * @param    args    no arguments needed
  49.      * @throws DocumentException
  50.      * @throws IOException
  51.      */
  52.     public static void main(String[] args)
  53.         throws IOException, DocumentException {
  54.         LoggerFactory.getInstance().setLogger(new SysoLogger());
  55.         File file = new File(DEST);
  56.         file.getParentFile().mkdirs();
  57.         new MergeAndCount().manipulatePdf(SRC, DEST);
  58.     }
  59. }

Resources

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