How to export MySQL database into Pdf file using PHP and Fpdf library?

In this tutorial you are going to see step by step how to generate PDF from MySQL Database using help of FPDF library in PHP.

In this example, we get MySQL table data by using PHP and then we will call FPDF functions to generate PDF from this MySQL data. First of all we need to understand whats is FPDF library functions.

What is FPDF?

FPDF is a PHP class which allows to generate PDF files with PHP, that is to say without using the FPDF library. F from FPDF stands for Free: you may use it for any kind of usage and modify it to suit your needs.

FPDF has other advantages: high level functions. Here is a list of its main features:
  • Choice of measure unit, page format and margins
  • Page header and footer management
  • Automatic page break
  • Automatic line break and text justification
  • Image support (JPEG, PNG and GIF)
  • Colors
  • Links
  • TrueType, Type1 and encoding support
  • Page compression

You can download FPDF library from here: Download

MySql Script to create Emplyee Table:

CREATE TABLE IF NOT EXISTS `employee` (
 `emp_id` int(11) NOT NULL AUTO_INCREMENT,
 `emp_name` varchar(50) DEFAULT NULL,
 `emp_profile` varchar(200) DEFAULT NULL,
  PRIMARY KEY (emp_id)
);
 
INSERT INTO `employee` (`emp_id`, `emp_name`, `emp_profile`) VALUES
(1, 'Varun Singh', 'Software Developer'),
(2, 'Rohit Singh ', 'Android Developer'),
(3, 'Amit Singh', 'iOS Developer'),
(4, 'Vinay Singh', '.Net Developer'),
(5, 'Deppak Singh', 'Web Developer');

generate-pdf.php:

<?php
$con = mysqli_connect("localhost","root"," ","database_name");
require('fpdf/fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
 
$pdf->SetFont('Arial','B',12);	
$ret ="SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` 
WHERE `TABLE_SCHEMA`='database_name' AND `TABLE_NAME`='employee'";
$query1 = $con -> prepare($ret);
$query1->execute();
$header=$query1->fetchAll(PDO::FETCH_OBJ);
$cnt=1;
if($query1->rowCount() > 0)
{
foreach($header as $heading) {
foreach($heading as $column_heading)
$pdf->Cell(39,12,$column_heading,1);
}}
//code for print data
$sql = "SELECT * from  employee";
$query = $con -> prepare($sql);
$query->execute();
$results=$query->fetchAll(PDO::FETCH_OBJ);
$cnt=1;
if($query->rowCount() > 0)
{
foreach($results as $row) {
$pdf->SetFont('Arial','',7);	
$pdf->Ln();
foreach($row as $column)
$pdf->Cell(39,7,$column,1);
} }
$pdf->Output();
?>