What are the best practices for handling PDF files with multiple pages in PHP using FPDI and TCPDF?

When working with PDF files with multiple pages in PHP using FPDI and TCPDF, it is important to properly handle the merging of multiple pages into a single PDF document. One way to achieve this is by iterating through each page of the source PDF files and importing them into the TCPDF instance using FPDI. By doing so, you can create a new PDF document with all the pages combined.

require_once('fpdf/fpdf.php');
require_once('tcpdf/tcpdf.php');
require_once('fpdi/fpdi.php');

// Create new TCPDF instance
$pdf = new TCPDF();

// Iterate through each source PDF file
$source_files = ['file1.pdf', 'file2.pdf', 'file3.pdf'];
foreach($source_files as $file) {
    // Create new FPDI instance
    $fpdi = new FPDI();
    
    // Add a page from the source file to the TCPDF instance
    $pagecount = $fpdi->setSourceFile($file);
    for ($i = 1; $i <= $pagecount; $i++) {
        $template = $fpdi->importPage($i);
        $size = $fpdi->getTemplateSize($template);
        $pdf->AddPage($size['h'] > $size['w'] ? 'P' : 'L');
        $pdf->useTemplate($template);
    }
}

// Output the combined PDF document
$pdf->Output('output.pdf', 'D');