What is the best approach for merging multiple PDFs into a single A4 PDF using PHP?

To merge multiple PDFs into a single A4 PDF using PHP, you can use the FPDI library to import each PDF file, adjust the page size to A4, and then merge them into a single PDF document. This can be achieved by iterating over each PDF file, importing its pages, and adding them to the final PDF document.

<?php
require_once('vendor/autoload.php');

use setasign\Fpdi\Fpdi;

// Initialize FPDI
$pdf = new Fpdi();

// Iterate over each PDF file to merge
$pdfFiles = ['file1.pdf', 'file2.pdf', 'file3.pdf'];

foreach ($pdfFiles as $file) {
    $pageCount = $pdf->setSourceFile($file);
    
    for ($i = 1; $i <= $pageCount; $i++) {
        $template = $pdf->importPage($i);
        $size = $pdf->getTemplateSize($template);
        
        $pdf->AddPage('L', 'A4');
        $pdf->useTemplate($template, 0, 0, $size['width'], $size['height'], true);
    }
}

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