iText in Action: Chapter 6: Working with existing PDFs


If you compile and execute this example, you'll get the following result:

You can download the full source code of Concatenate, or read it here:

 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to:
 * This example only works with the AGPL version of iText.
package part2.chapter06;
import java.sql.SQLException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfReader;
import part1.chapter02.MovieHistory;
import part1.chapter02.MovieLinks1;
public class Concatenate {
    /** The resulting PDF file. */
    public static final String RESULT
        = "results/part2/chapter06/concatenated.pdf";
     * Main method.
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException
     * @throws SQLException
    public static void main(String[] args)
        throws IOException, DocumentException, SQLException {
        // using previous examples to create PDFs
        String[] files = { MovieLinks1.RESULT, MovieHistory.RESULT };
        // step 1
        Document document = new Document();
        // step 2
        PdfCopy copy = new PdfCopy(document, new FileOutputStream(RESULT));
        // step 3;
        // step 4
        PdfReader reader;
        int n;
        // loop over the documents you want to concatenate
        for (int i = 0; i < files.length; i++) {
            reader = new PdfReader(files[i]);
            // loop over the pages in that document
            n = reader.getNumberOfPages();
            for (int page = 0; page < n; ) {
                copy.addPage(copy.getImportedPage(reader, ++page));
        // step 5
Powered by GeSHi

The Concatenate example is part of the book iText in Action (ISBN 9781935182610).

It's a small standalone application. You can use this example for inspiration, but please read the book if there's something you don't understand about the example. You'll find more info in Chapter 6. Note that this example depends on MovieLinks1, MovieHistory, and maybe some other examples.

Keywords for this example: Concatenate PDFs, Existing PDFs, PdfCopy, PdfImportedPage, PdfReader

If you want this example to work, you need the following jars: iText.jar, hsqldb.jar

This example uses the following resources: filmfestival.script.