how-to-merge-pdf-files-in-symfony-5

How To Merge PDF Files In Symfony 5

Avatar photoPosted by

Hello there and welcome to this blog, I will be showing you how to merge PDF files in Symfony 5. PDF has been one of the most commonly used document formats today. Most of the web apps have functionality that generates a PDF for the invoice. receipts, reports, and others, and some web apps do pdf merging.

What is PDF? It stands for Portable Document Format. It is a file format developed by Adobe to present or display documents in a manner independent of application software, hardware, and operating systems.

What is SymfonySymfony is a PHP framework used to develop web applications, APIs, microservices, and web services. Symfony is one of the leading PHP frameworks for creating websites and web applications.

Now we will proceed with the actual setup and code for merging PDF files. We will assume that these files are located in the /public folder of the Symfony project directory.

Step 1: Install Symfony 5

First, select a folder that you want Symfony to be installed then execute this command on Terminal or CMD to install:

Install via composer:

composer create-project symfony/website-skeleton symfony-5-pdf-merge

Install via Symfony CLI:

symfony new symfony-5-pdf-merge --full

Step 2: Install Packages

We will install now setasign/fpdf and setasign/fpdi packages. We will be using these packages to read and generate PDF. If you want to know more about the packages, open the link here for the setasign/fpdf and setasign/fpdi.

setasign/fpdf – This package contains a PHP class that can be used to generate PDF files using pure PHP. The F on FPDF means free: the developer may use it for any kind of usage and modify it depending on its needs. You might want to read more about FPDF on this link.

setasign/fpdi – This package contains a collection of PHP classes that allows us to read pages from existing PDF files and used them as templates for FPDF. You might want to read more about FPDF on this link.

composer require setasign/fpdf
composer require setasign/fpdi

Step 3: Set Database Configuration

We must configure our database to avoid errors. Open the .env file and set database configuration. We will be using MySQL on this tutorial. Uncomment the DATABASE_URL variable for MySQL and updates its configs. Make sure you commented out the other DATABASE_URL variables.

.env

# In all environments, the following files are loaded if they exist,
# the latter taking precedence over the former:
#
#  * .env                contains default values for the environment variables needed by the app
#  * .env.local          uncommitted file with local overrides
#  * .env.$APP_ENV       committed environment-specific defaults
#  * .env.$APP_ENV.local uncommitted environment-specific overrides
#
# Real environment variables win over .env files.
#
# DO NOT DEFINE PRODUCTION SECRETS IN THIS FILE NOR IN ANY OTHER COMMITTED FILES.
#
# Run "composer dump-env prod" to compile .env files for production use (requires symfony/flex >=1.2).
# https://symfony.com/doc/current/best_practices.html#use-environment-variables-for-infrastructure-configuration
    
###> symfony/framework-bundle ###
APP_ENV=dev
APP_SECRET=e0710317861221371d185cc932acd15b
###< symfony/framework-bundle ###
    
###> doctrine/doctrine-bundle ###
# Format described at https://www.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/configuration.html#connecting-using-a-url
# IMPORTANT: You MUST configure your server version, either here or in config/packages/doctrine.yaml
#
# DATABASE_URL="sqlite:///%kernel.project_dir%/var/data.db"
 DATABASE_URL="mysql://db_user:db_password@127.0.0.1:3306/db_name?serverVersion=5.7"
# DATABASE_URL="postgresql://db_user:db_password@127.0.0.1:5432/db_name?serverVersion=13&charset=utf8"
###< doctrine/doctrine-bundle ###

Step 3: Create A Controller

We will now create our controller, run this command to create a controller:

php bin/console make:controller PdfMergeController

After executing the command, open this file ‘src\Controller\ PdfMergeController .php’, and add this code:

src\Controller\PdfMergeController.php

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use setasign\Fpdi\Fpdi;

class PdfMergeController extends AbstractController
{
    /**
     * @Route("/pdf/merge", name="pdf_merge")
     */
    public function index(): Response
    {
        $files = ['file-1.pdf', 'file-2.pdf'];
        $pdf = new Fpdi();
 
        foreach ($files as $file) {
            // set the source file and get the number of pages in the document
            $pageCount =  $pdf->setSourceFile($file);
 
            for ($i=0; $i < $pageCount; $i++) { 
                //create a page
                $pdf->AddPage();
                //import a page then get the id and will be used in the template
                $tplId = $pdf->importPage($i+1);
                //use the template of the imporated page
                $pdf->useTemplate($tplId);
            }
        }
 
        //return the generated PDF
        return $pdf->Output();     
    }
}

make sure you will change the file path on the $files variable. In this tutorial the location of the files is found on the /public folder of the Symfony project, you can use any file path on your preference to test the merging of pdf files. make sure to use a correct file path to avoid errors when merging files.

Step 4 : Run the Application

After finishing the steps above, you can now run your application by executing the command below:

symfony server:start

After successfully running your app, open this URL in your browser:

https://localhost:8000/pdf/merge

This URL will load the merged PDF files on the browser. So there you have now functionality that merges PDF files.