How can FPDI & FDPF be used to append multiple pages from an existing PDF document to a new PDF?

To append multiple pages from an existing PDF document to a new PDF using FPDI & FPDF, you can iterate through the existing PDF document, import each page using FPDI, and then add each imported page to the new PDF using FPDF.

// Include the FPDI and FPDF libraries
require_once('fpdf/fpdf.php');
require_once('fpdi/fpdi.php');

// Create a new instance of FPDF
$pdf = new FPDF();

// Create a new instance of FPDI
$pdfReader = new FPDI();

// Open the existing PDF file
$pdfReader->setSourceFile('existing.pdf');

// Iterate through each page of the existing PDF
for ($page = 1; $page <= $pdfReader->setPageCount(); $page++) {
    // Import the page
    $templateId = $pdfReader->importPage($page);
    
    // Get the size of the imported page
    $size = $pdfReader->getTemplateSize($templateId);
    
    // Add a new page to the new PDF
    $pdf->AddPage($size['orientation'], $size['size']);
    
    // Use the imported page as a template
    $pdf->useTemplate($templateId);
}

// Output the new PDF
$pdf->Output('new.pdf', 'F');