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.
Start by installing the following composer packages:
composer require setasign/fpdf setasign/fpdi-fpdf
These two libraries are all you need to edit PDFs.
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
For example, the below line sets the
X coordinates to
Y coordinates to
89. This is the position with in the PDF where I want the cell to appear.
Then, I create a cell with:
- 100% width (first parameter =
- 10 height (second parameter =
- Text is set to
Niraj Shah(third parameter)
- 1px border (forth parameter =
- no fill (fifth parameter =
- center alignment (last parameter =
C. Can also use
$pdf->Cell(0, 10, 'Niraj Shah', 1, 0, 'C');
Then, to remove the border, set the third parameter to
$pdf->Cell(0, 10, 'Niraj Shah', 0, 0, 'C');
Or to change the alignment of the text, change the last parameter to either
$pdf->Cell(0, 10, 'Niraj Shah', 1, 0, 'L');
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.
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.
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.