In a recent project, I was asked to create a dynamically generated PDF with the user’s information. In my research, I found that using FPDF was the best the best way to achieve the client’s requirements. Here is a quick tutorial on how you can use a existing PDF with dynamic content using only PHP. This particular example uses composer and less than 50 lines of code.
Installation
Start by installing the following composer packages:
composer require setasign/fpdf setasign/fpdi-fpdf
These two libraries are all you need to edit PDFs.
The Code
Before creating the code, you first need to to find a existing PDF to use. In this tutorial, I will be using the following template. Upload the file you want to use within your project folder so you can reference it in your code.
As for the code, this is what I used:
See the comments within the code to see what’s going on – most of it’s pretty self-explanatory, thanks to the straight-forward function names.
As the PDF I’m using has space for five bits of text, I’ve created 5 cells within the PDF using PHP. To help align these cells, the third parameter is set to 1
, this means a border has been added to see where the cell appears. When you are happy with the placement (using SetXY
) and size (using the first two parameters in Cell
), you can set this to 0
.
For example, the below line sets the X
coordinates to 10
, and Y
coordinates to 89
. This is the position with in the PDF where I want the cell to appear.
$pdf->SetXY(10, 89);
Then, I create a cell with:
- 100% width (first parameter =
0
) - 10 height (second parameter =
10
) - Text is set to
Niraj Shah
(third parameter) - 1px border (forth parameter =
1
) - no fill (fifth parameter =
0
. Use1
for fill) - center alignment (last parameter =
C
. Can also useL
andR
).
$pdf->Cell(0, 10, 'Niraj Shah', 1, 0, 'C');
Then, to remove the border, set the third parameter to 0
:
$pdf->Cell(0, 10, 'Niraj Shah', 0, 0, 'C');
Or to change the alignment of the text, change the last parameter to either L
, R
or C
:
$pdf->Cell(0, 10, 'Niraj Shah', 1, 0, 'L');
Example
With the above code and PDF template, my final output (with borders enabled) results in:
Please note that white border has been removed in screenshot.
Final Result
After updating the code to remove the borders, the final PDF looks like:
The user can then choose to download the PDF or print it using their browser. You can see the downloaded version here.
Source Code
If you would like to see the entire source code I used, along with example PDF and composer settings, you can download the source code ZIP here.
If you have any issues, comments, suggestions, etc., feel free to leave a comment below.