Merge PDF files with PHP

There are several ways to merge PDF files using PHP. One way is to use the FPDI library, which allows you to import an existing PDF file and add pages to it. Here is an example of how you can use FPDI to merge two PDF files:

<?php

// include FPDI
require_once '/path/to/fpdi.php';

// initiate FPDI
$pdf = new FPDI();

// add a page
$pdf->AddPage();

// set the source file
$pdf->setSourceFile('/path/to/first.pdf');

// import page 1
$tplIdx = $pdf->importPage(1);

// use the imported page as the template
$pdf->useTemplate($tplIdx);

// set the source file
$pdf->setSourceFile('/path/to/second.pdf');

// import page 1
$tplIdx = $pdf->importPage(1);

// use the imported page as the template
$pdf->useTemplate($tplIdx);

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

This code will import the first page of each of the two input PDF files and create a new PDF with those two pages. You can repeat the setSourceFile and importPage/useTemplate steps to add additional pages from other PDF files.

Watch a course Learn object oriented PHP

Another option is to use the PDFMerger library, which provides a simple interface for merging PDF files. Here is an example of how to use PDFMerger to merge two PDF files:

<?php

// include PDFMerger
require_once '/path/to/PDFMerger.php';

// create a new PDFMerger object
$pdf = new PDFMerger();

// add the first PDF
$pdf->addPDF('/path/to/first.pdf', 'all');

// add the second PDF
$pdf->addPDF('/path/to/second.pdf', 'all');

// output the merged PDF
$pdf->merge('file', '/path/to/merged.pdf');

This code will merge the two input PDF files into a new file called merged.pdf. You can use the addPDF function to add additional PDF files to the merge.