Import pages from existing PDF documents and use them as templates in FPDF

FPDI

Import pages from existing PDF documents and use them as templates in FPDF

Fake a concatenation of PDF documents

Yes, it's just a fake and not a real concatenation. As FPDI only imports single pages the structure of the resulting document is completely different from the one of the original. Also FPDI is not able to handle dynamic content like bookmark outlines, form fields, or any other annotation. These content get lost.

(For real concatenation see: SetaPDF-Merger component - this component works without modifying the internal structur of PDF documents and will keep all content.)

PHP
<?php
require_once('fpdf.php');
require_once('fpdi.php');

class ConcatPdf extends FPDI
{
    public $files = array();

    public function setFiles($files)
    {
        $this->files = $files;
    }

    public function concat()
    {
        foreach($this->files AS $file) {
            $pageCount = $this->setSourceFile($file);
            for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
                $tplIdx = $this->ImportPage($pageNo);
                $s = $this->getTemplatesize($tplIdx);
                $this->AddPage($s['w'] > $s['h'] ? 'L' : 'P', array($s['w'], $s['h']));
                $this->useTemplate($tplIdx);
            }
        }
    }
}

$pdf = new ConcatPdf();
$pdf->setFiles(array('Boombastic-Box.pdf', 'Fantastic-Speaker.pdf', 'Noisy-Tube.pdf'));
$pdf->concat();

$pdf->Output('concat.pdf', 'I');