Categories
PHP

Concatenate PDF in PHP

As requirement for one project we need it to concatenate PDF files to have just one file as input.

First download in your work space TCPDF and FPDI

Class to concatenate pdf, pdfConcat.php:

require_once("tcpdf/tcpdf.php");
require_once("fpdi/fpdi.php");

class concat_pdf extends FPDI {
     var $files = array();
     function setFiles($files) {
          $this->files = $files;
     }
     function concat() {
          foreach($this->files AS $file) {
               $pagecount = $this->setSourceFile($file);
               for ($i = 1; $i <= $pagecount; $i++) {
                    $tplidx = $this->ImportPage($i);
                    $s = $this->getTemplatesize($tplidx);
                    $this->AddPage(’P', array($s['w'], $s['h']));
                    $this->useTemplate($tplidx);
               }
          }
     }
}

Usage:

include_once("pdfConcat.php");
$pdf =& new concat_pdf();
$pdf->setFiles(array("doc.pdf","pauta.pdf", "4bp.pdf", "5bp.pdf"));
$pdf->concat();
$pdf->Output("newpdf.pdf", "I");

After this I recommend to you to keep the file already merged in the server, then you will not need to generate it another time. To do this you can use $pdf->Output(“newpdf.pdf”, “F”); instead.