Merge PDF files with PHP
There are several ways to merge PDF files using 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:
Example of merging PDF files with PHP
Install the library via Composer:
composer require setasign/fpdi<?php
// include FPDI via Composer autoloader
require 'vendor/autoload.php';
use setasign\Fpdi\Fpdi;
try {
// initiate FPDI
$pdf = new Fpdi();
// set the source file
$pdf->setSourceFile('/path/to/first.pdf');
// import page 1
$tplIdx = $pdf->importPage(1);
// use the imported page as the template
// FPDI v2 automatically sets the page size to match the imported PDF, avoiding A4 cropping
$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');
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
}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.
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:
Example of merging PDF files with PDFMerger in PHP
Install via Composer: composer require pdfmerger/pdfmerger
<?php
// include PDFMerger via Composer autoloader
require 'vendor/autoload.php';
use PDFMerger\PDFMerger;
try {
// 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');
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
}Note: PDFMerger is unmaintained and may conflict with modern PHP/FPDI versions. Consider using FPDI for active support.
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.