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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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:

1
2
3
4
5
$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.

Follow me

Abhishek Gupta

I am Abhishek from Lucknow (India). I have been working as a software engineer from last 6+ years, and its my passion to learn new things and implement them as a practice.
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