Splitting a PDF file

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

7th November 2015
admin-marketing

iText 5 is no longer being developed, except for security fixes. Click the following link to see an updated example for iText 7.

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

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