Merge PDF pages in Java and iText

A Java method that correctly merges PDF pages using iTextPDF version 5. The result is a PDF containing a super page.

//Based on
public void mergePages(String source, String destination) throws IOException, DocumentException {
  PdfReader reader = new PdfReader(source);
  // The PDF page size is fetched as a Rectangle with an width and a height
  Rectangle pageSize = reader.getPageSize(1);
  // The resultig page will have the total height of the combined pages
  Rectangle resultSize = new Rectangle(pageSize.getWidth(), 2 * pageSize.getHeight());

  Document document = new Document(resultSize, 0, 0, 0, 0);
  PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(destination));
  // Document needs to be opened before getting the direct content;
  PdfContentByte canvas = writer.getDirectContent();

  // Make sure that the resulting document has a page

  float offsetY = 0;
  int pageNo = reader.getNumberOfPages();

  // Since the point (X,Y) = (0,0) is the left bottom corner of the PDF it is easyer to start
  // placing the pages from the last to the first.
  for (int i = pageNo; i > 0; i--) {
    PdfImportedPage page = writer.getImportedPage(reader, i);
    canvas.addTemplate(page, 0, offsetY);

    // Move up the Y axis
    offsetY += pageSize.getHeight();

  // Close resources

Merging PDF files is one of those simple tasks that could drive you crazy if you are in need of a quick solution. There are a lot of buggy / incorrect examples out there, and the most reliable way to have a good insight into this is to read chapter 6 from iText in Action.