Downloading PDFs online is quite common, tickets to a concert, invoices and installation instructions are some of the regular PDFs in everyones downloads-folder. In this post I will go through how you can edit your PDF's using FPDF and FPDI.
FPDF and FPDI
FPDI is a collection of PHP classes faciliating developers to read pages from an existing PDF document and use them as templates in FPDF. We used FPDI to import the exisitng PDF-template and then FPDF to populate the PDF with values.
Getting started
It is very easy to get started, by adding both fpdi and fpdf with composer:
composer require setasign/fpdi
composer require setasign/fpdi
When the installation is complete, create a new php file and add the following snippet:
Open the file in the browser and you should see a red title inside your PDF, if you have a PDF with multiple pages that you would like to edit, you can use the following code:
Reload the page, you should now see a title in the top left corner on the first page of your pdf, and on the second page, a title in the top right corner.
Instead of showing the PDF directly in the browser, you can add different arguments to the Output method:
$pdf->Output('generated-pdfs/name-of-your-new.pdf','F');
Create a folder inside your project called generated-pdfs, reload your page and you will have a new PDF inside your newly created folder.
$pdf->Output('name-of-your-new.pdf','D');
If you want the file to be downloaded directly, you can use the above code instead, reload the page and you will start a download of your PDF.
By extending the code above, you could edit your PDF's with dynamic content, maybe populate it with values from a form or any other information on your website.