Contents
Hi there and welcome to our blog, Today, I will be showing you how to add page numbers to PDF in Symfony 6. PDF has been one of the most commonly used document formats today. This tutorial is made as easy as possible for the readers to easily learn.
What is a 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 Symfony? Symfony 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 6
First, select a folder where you want Symfony to be installed then execute this command on Terminal or CMD to install:
Install via composer:
composer create-project symfony/skeleton:"6.4.*" symfony-6-pdf-page-numbering
cd symfony-6-pdf-page-numbering
composer require webapp
Install via Symfony CLI:
symfony new symfony-6-pdf-page-numbering --version="6.4.*" --webapp
Step 2: Install Packages
We will install now setasign/fpdf and setasign/fpdi packages. We will be using these packages to read and generate PDFs. 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 the database configuration. We will be using MySQL in this tutorial. Uncomment the DATABASE_URL variable for MySQL and update its configs. Make sure you comment 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 4: Create PDF Class
We will now create a PDF class, this class will extend the FPDI. Before we create this class, we will create first a folder in /src which will be named Util.
After that we will now create the PDF class, copy the code below:
src\Util\PDF.php
<?php
namespace App\Util;
use setasign\Fpdi\Fpdi;
class PDF extends FPDI
{
function Footer()
{
// Position at 1.5 cm from bottom
$this->SetY(-15);
// Arial italic 8
$this->SetFont('Arial','I',8);
// Page number
$this->Cell(0,10,'Page '.$this->PageNo().'/{nb}',0,0,'C');
}
}
Step 5: Create A Controller
We will now create our controller, run this command to create a controller:
php bin/console make:controller PdfNumberingController
After creating a controller add these codes:
src\Controller\PdfNumberingController.php
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use App\Util\PDF;
class PdfNumberingController extends AbstractController
{
/**
* @Route("/pdf/numbering", name="pdf_numbering")
*/
public function index(): Response
{
$pdf = new PDF();
// // set the source file
$pageCount = $pdf->setSourceFile('file-2.pdf');
$pdf->AliasNbPages();
for ($i=1; $i <= $pageCount; $i++) {
//import a page then get the id and will be used in the template
$tplId = $pdf->importPage($i);
//create a page
$pdf->AddPage();
//use the template of the imporated page
$pdf->useTemplate($tplId);
}
$pdf->Output();
}
}
Step 6: 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:
http://localhost:8000/pdf/numbering
This URL will load the numbered pages of the PDF file on the browser. So there you have now functionality that adds page numbers on PDF files.