Splitting a PDF file

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

31st May 2016
iText PDF

Switch code for this example

MergeAndCount.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.
  10.  */
  11. package com.itextpdf.samples.sandbox.merge;
  12.  
  13. import com.itextpdf.kernel.pdf.PdfDocument;
  14. import com.itextpdf.kernel.pdf.PdfReader;
  15. import com.itextpdf.kernel.pdf.PdfWriter;
  16. import com.itextpdf.kernel.utils.PageRange;
  17. import com.itextpdf.kernel.utils.PdfSplitter;
  18. import com.itextpdf.test.annotations.type.SampleTest;
  19.  
  20. import org.junit.experimental.categories.Category;
  21.  
  22. import java.io.FileNotFoundException;
  23. import java.io.IOException;
  24. import java.util.List;
  25.  
  26. @Category(SampleTest.class)
  27. public class MergeAndCount {
  28.     public static final String DESTFOLDER
  29.             = "./samples/target/test/resources/sandbox/merge/";
  30.     public static final String RESOURCE
  31.             = "./samples/src/test/resources/pdfs/Wrong.pdf";
  32.  
  33.     public static void main(String[] args) throws IOException {
  34.         new MergeAndCount().manipulatePdf(DESTFOLDER);
  35.     }
  36.  
  37.     public void manipulatePdf(final String destFolder) throws IOException {
  38.         PdfDocument pdfDoc = new PdfDocument(new PdfReader(RESOURCE));
  39.  
  40.         List<PdfDocument> splitDocuments = new PdfSplitter(pdfDoc) {
  41.             int partNumber = 1;
  42.  
  43.             @Override
  44.             protected PdfWriter getNextPdfWriter(PageRange documentPageRange) {
  45.                 try {
  46.                     return new PdfWriter(destFolder + "splitDocument1_" + String.valueOf(partNumber++) + ".pdf");
  47.                 } catch (FileNotFoundException e) {
  48.                     throw new RuntimeException();
  49.                 }
  50.             }
  51.         }.splitBySize(200000);
  52.  
  53.         for (PdfDocument doc : splitDocuments)
  54.             doc.close();
  55.         pdfDoc.close();
  56.     }
  57. }

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