Skip to content

How to Merge PDF Files using Laravel, PHP

Last updated on November 17, 2022

Laravel merge pdfs

In this tutorial, you will learn how to merge multiple pdf files in your Laravel application. We gonna write a simple PHP script to merge one or more pdf files (Laravel merge pdfs), into a single file. This script will work with any version of the Laravel framework.

We gonna install the setasign\Fpdi library using composer and we’ll be using it to merge multiple pdf files into a single file.

Let’s start implementing it by installing the Laravel framework. This tutorial assumes that your computer already has PHP and Composer installed.

Step 1: Install the Laravel framework with the composer.
you can create a new Laravel project by using Composer directly with the below command. After the application has been created, you may start Laravel’s local development server using the Artisan CLI’s serve command as shown below.

composer create-project laravel/laravel example-app

cd example-app

php artisan serve

Step 2: Install FPDI Package using the composer

composer require setasign/fpdf
composer require setasign/fpdi

Step 3: Open the existing controller file or create a new controller with php artisan make:controller MergePDFController command and copy the below methods to it.


namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use setasign\Fpdi\Fpdi;

class MergePDFController extends Controller
    public function process(Request $request) {
        $files = [Storage::disk('local')->path("first.pdf"), Storage::disk('local')->path('second.pdf')];
        return response()->file(Storage::disk('local')->path('newtest.pdf'));


    public function merge($files, $outputPath)
        $fpdi = new FPDI;
        foreach ($files as $file) {
            $filename  = $file;
            $count = $fpdi->setSourceFile($filename);
            for ($i=1; $i<=$count; $i++) {
                $template   = $fpdi->importPage($i);
                $size       = $fpdi->getTemplateSize($template);
                $fpdi->AddPage($size['orientation'], array($size['width'], $size['height']));

        $fpdi->Output($outputPath, 'F');

Step 4: Define a route in web.php to test the functions.

Route::get('/merge-pdfs', [\App\Http\Controllers\MergePDFController::class,'process']);

Step5: Now start your application php artisan serve and access it at http://localhost:8000/merge-pdfs

You can see the output files at:

0 0 votes
Article Rating
Notify of

Most Voted
Newest Oldest
Inline Feedbacks
View all comments