How to generate PDF documents using TCPDF in PHP
Install TCPDF via Composer and create a basic PHP script to generate a PDF with text, tables, and images.
This tutorial explains how to install TCPDF and create a functional PDF file from a PHP script. The steps apply to PHP 8.3.x environments running on Linux or Windows servers.
Prerequisites
- PHP 8.3.x installed and running
- Composer 2.7.x installed globally
- Basic knowledge of PHP syntax and file structure
- Internet connection to download the TCPDF library
Step 1: Create a project directory
Create a new folder to hold your PHP project and files. This keeps your code organized and separate from system directories.
mkdir ~/projects/tcpdf-demo
cd ~/projects/tcpdf-demo
Verify that the directory was created successfully by listing its contents. You will see an empty folder ready for code.
ls -la
total 8
drwxr-xr-x 2 user user 4096 date
Step 2: Initialize a Composer project
Run the Composer init command to create a default composer.json file. This file manages your project dependencies and ensures TCPDF is installed correctly.
composer init --name="tcpdf-demo" --description="TCPDF Demo Project" --type=project
You will see a file named composer.json created in your current directory. This file will store the configuration for your project.
- Writing ./composer.json
Loading composer repositories with package information
Updating dependencies
Nothing to install, update or remove
Generating autoload files
Step 3: Install TCPDF via Composer
Use Composer to install the latest stable version of TCPDF. This command downloads the library and its required dependencies automatically.
composer require tecnickcom/tcpdf
Composer will resolve dependencies and install the package. You will see the specific version number being installed, typically around 6.7.x for PHP 8.3 compatibility.
./composer.json has been updated
Running composer update tecnickcom/tcpdf
Loading from cache
Installing tecnickcom/tcpdf (v6.7.6)
Generating autoload files
1 package you are using is looking for funding.
Use the `composer fund` command to find out more!
Step 4: Create a PHP script to generate a PDF
Create a new file named generate-pdf.php in your project directory. This file will contain the code to initialize TCPDF and add content to the document.
touch generate-pdf.php
Edit the file and paste the following code. This script initializes the TCPDF class, sets the page format, adds a title, a paragraph, a table, and an image.