Concatenate PDF in PHP

As requirement for one of my projects, I needed to concatenate multipe PDF files provided by the user into just one file.

To achieve this, we need the TCPDF and FPDI libraries.

Class to concatenate pdf, Pdf_concat.class.php:

require_once('./includes/tcpdf/config/lang/eng.php');
require_once('./includes/tcpdf/tcpdf.php');
require_once('./includes/fpdi/fpdi.php');

class Pdf_concat 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:

$file2merge=array('file1.pdf', 'folder/file2.pdf', file3.pdf);
$pdf = new Pdf_concat();
$pdf->setFiles($file2merge);
$pdf->concat();
$pdf->Output('folder/newfile.pdf', "I");

$pdf->Output(“newpdf.pdf”, “I”) shows the merged file on screen.

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 and save the file.

Abhishek Gupta
Follow me
Latest posts by Abhishek Gupta (see all)

6 Replies to “Concatenate PDF in PHP”

  1. I got the fix for that,need to set the Header and footer to false in the beginning of the concat function

    $this->setPrintHeader(false);
    $this->setPrintFooter(false);

    Cheers

Leave a Reply