A PDF is one of the most common documents in the e-commerce industry and the digital world. E-bills are mostly generated in e-commerce are of PDF format but when it comes to creating the PDF files dynamically we need a proper code to handle it. PHP has lots of libraries to generate PDF files dynamically. Today we are going to use a lightweight and the easiest library which is FPDF.
What is FPDF?
FPDF is a Free-PDF PHP library to generate PDF files. You can download and customize the code to fit your needs. It is easier than the other PDF libraries. You only need to include the PHP class and it's ready to use. It supports the page format, margins, image, colors, links, page break, etc. features which makes it more usable and robust. You can download it from FPDF from its official website.
Creating a PDF file
After downloading the FPDF you need to create a PHP file and include the following code in it.
require('fpdf.php'); //create a FPDF object $mypdf=new FPDF(); //setting document properties $mypdf->SetAuthor('John Doe'); $mypdf->SetTitle('My First PDF'); //seting font & font color for the entire document $mypdf->SetFont('Helvetica','B',22); $mypdf->SetTextColor(50,60,100); //adding a page $mypdf->AddPage('P'); //inserting an image with a link $mypdf->Image('logo.png',10,20,33,0,' ','http://www.fpdf.org/'); //Set x and y position of the text on page and write content with reduced font size $mypdf->SetXY (10,50); $mypdf->SetFontSize(10); $mypdf->Write(5,'Hurray! You have generated a PDF.'); //Output the document to browser $mypdf->Output('myFirstFile.pdf','I');
Now understanding the flow of code :
Including the required file to create PDF
Now we are creating a new object of FPDF class
$mypdf= new FPDF();
The FPDF contructor can takes parameters for orientation, measure unit, and page size.
setting properties of the PDF file
$mypdf->SetAuthor('John Doe'); $mypdf->SetTitle('My First PDF ');
Setting font and text color for whole PDF page before creating the page. Here 'Helvetica' is the font name and 'B' is the font type (Bold) and '22' is font size.
Now creating a page with a layout mode 'P'. P stands for portrait & L stands for landscape.
Now adding an image with a link we use Image function.
Now we are writing text to the PDF, which displays a success message.
$mypdf->SetXY(10,50); $mypdf->SetFontSize(10); $mypdf->Write(5,'Hurray! You have generated a PDF.');
Finally, we are sending the output file to the browser, using the FPDF Output function.
Here we are passing the name of the output file and the destination "I". The "I" parameter will send the output to the browser.
So this is how we can create PDF files dynamically with PHP