PHP PDF Merge Files

This is a simple tutorial on how to merge PDF files with PHP. Starting, you’ll want to download the libraries used. You can download them below into a folder called “inc” within your project.

Pick the latest version for each!

FPDF – www.fpdf.org/en/download.php Create a folder called “fpdf” within your “inc” folder and then take just the file “fpdf.php” from the download.

FPDI – www.setasign.com/products/fpdi/downloads Create a folder called “fpdi” within your “inc” folder and then copy all of the contents in the “src” folder from the download to that “fpdi” directory. That’s all that you will need.

Great, now that you have your libraries we can include our script from below to merge our pdfs. You will need to place the pdf’s you want to merge in the root directory of your project.

//Include FPDF
require_once(__DIR__ . '/inc/fpdf/fpdf.php');

//Include FPDI
require_once(__DIR__ . '/inc/fpdi/autoload.php');
use setasign\Fpdi\FPDI;

//Init FPDI object
$pdf = new FPDI();

//Create files array
$files = [
	'page 1.pdf', 
	'page 2.pdf', 
	'page 3.pdf'
];

//Iterate over files and their pages
foreach ($files as $file) {
    $pageCount = $pdf->setSourceFile($file);
    for ($i = 0; $i < $pageCount; $i++) {
        $tpl = $pdf->importPage($i + 1);
        $pdf->addPage();
        $pdf->useTemplate($tpl);
    }
}

/*
	Output PDF
	F - Save to file
	D - Start download
*/
$pdf->Output('F','page 1-3.pdf');

Now that you have added the script, All you will need to do is update the files to match the names of the PDF’s you’d like to merge and the output file name. Voila, you have merged your PDF’s and that resulting PDF should be in your root directory.

For my test environment I used Xampp and you can download the project directory I used here excluding the libraries you’ll need to download from above.

1 Response
  1. Sunny Thomas

    Thank you very much the plugin is working fine. I have one issue, if the pdf sizes are different then the pdf are not merged and error is displayed. Can that also be resolved

Leave a Reply

Your email address will not be published. Required fields are marked *

Last Updated:
Author: Brice Viland