How to create PDF with PHP?

There are many web applications that require output such as invoices, contracts or its web pages in PDF format. PHP has PDFlib library to create PDF dynamically but it’s very vast and need a lot of time to study and understand. So there are another PHP class FPDF that allows you to generate PDF files easily without using the PDFlib library.

The FPDF library is free and can be downloaded from the official website’s download section. The download package contains all necessary files, along with some tutorials on how to use it. Below is PHP example code to create PDF from MySQL table data using FPDF library. You must download and extract the FPDF package in the folder where the PHP file with the code is located to run this example.

PHP Script to create PDF from MySQL with PHP

$sql = "SELECT id, employee_name, employee_salary, employee_age FROM employee LIMIT 10";
$resultset = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
$pdf = new FPDF();
while ($field_info = mysqli_fetch_field($resultset)) {
while($rows = mysqli_fetch_assoc($resultset)) {
foreach($rows as $column) {

Hope you have you have downloaded and extracted the FPDF package inside a folder on your server. Now create a new file called createpdf.php inside the same folder on your server and insert the above code. You can then access your example file createpdf.php through browser.

MySQL Table and Data

You just need to run this script for the MySQL data.
-- Table structure for table `employee`
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'primary key',
`employee_name` varchar(255) NOT NULL COMMENT 'employee name',
`employee_salary` double NOT NULL COMMENT 'employee salary',
`employee_age` int(11) NOT NULL COMMENT 'employee age',
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='datatable demo table' AUTO_INCREMENT=58 ;
-- Dumping data for table `employee`
INSERT INTO `employee` (`id`, `employee_name`, `employee_salary`, `employee_age`) VALUES
(1, 'Tiger Nixon', 320800, 61),
(2, 'Garrett Winters', 170750, 63),
(3, 'Ashton Cox', 86000, 66),
(4, 'Cedric Kelly', 433060, 22),
(5, 'Airi Satou', 162700, 33),
(6, 'Brielle Williamson', 372000, 61),
(7, 'Herrod Chandler', 137500, 59),
(8, 'Rhona Davidson', 327900, 55),
(9, 'Colleen Hurst', 205500, 39),
(10, 'Sonya Frost', 103600, 23);

Demo [sociallocker]Download[/sociallocker]

You may like these posts