Friday, July 22, 2011

Merge PDF documents with Zend_Pdf

Merging two or more PDF files with Zend_Pdf component of the Zend Framework is really simple. You just need to load the documents into Zend_Pdf instances and then iterate over their pages:

// load PDF documents
$pdf1 = Zend_Pdf::load('first.pdf');
$pdf2 = Zend_Pdf::load('second.pdf');
// we will merge our two PDF files into a new Zend_Pdf object
$pdfMerged = new Zend_Pdf();
// add all pages from the first PDF to our new document
foreach($pdf1->pages as $page){
    $clonedPage = clone $page;
    $pdfMerged->pages[] = $clonedPage;
}
// add all pages from the second PDF to our new document
foreach($pdf2->pages as $page){
    $clonedPage = clone $page;
    $pdfMerged->pages[] = $clonedPage;
}
unset($clonedPage);
// send the merged PDF document to browser
header('Content-type: application/pdf');

echo $pdfMerged->render();

2 comments:

  1. does this work with xfa pdf files?

    ReplyDelete
  2. I did'nt tried it. After a short time i started to use tcpdf. http://www.tcpdf.org/

    ReplyDelete