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/fpdf.php');
require_once('fpdi2/src/autoload.php');

class ConcatPdf extends \setasign\Fpdi\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++) {
                $pageId = $this->importPage($pageNo);
                $s = $this->getTemplatesize($pageId);
                $this->AddPage($s['orientation'], $s);
                $this->useImportedPage($pageId);
            }
        }
    }
}

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

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