In this tutorial I will explain here how to generate PDF from MySQL Data using PHP. You are going to see how to convert MySQL Data into PDF using FPDF library.
Download first FPDF here.
What id FPDF ?
FPDF is a PHP class which allows to generate PDF files with PHP, that is to say without using the PDFlib 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
The following snippet show a basic PDF generated with FPDF :
<?php require('fpdf/fpdf.php'); $pdf = new FPDF(); $pdf->AddPage(); $pdf->SetFont('Arial','B',12); $pdf->Cell(46,12,$column_heading,1); $pdf->Output(); ?>
First a db with empadata. Under db empdata create table tblemployee- Structure of tblemployee
CREATE TABLE IF NOT EXISTS `tblemployee` ( `EmpId` int(11) NOT NULL, `EmpName` varchar(100) DEFAULT NULL, `EmpDepartment` varchar(100) DEFAULT NULL, `EmpRegDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1; INSERT INTO `tblemployee` (`EmpId`, `EmpName`, `EmpDepartment`, `EmpRegDate`) VALUES (1, 'Anuj kumar', 'Development', '2017-06-08 01:47:41'), (2, 'Amit ', 'HR', '2017-07-02 09:47:41'), (3, 'Garima', 'Accountant', '2016-10-14 12:48:31'), (4, 'John', 'Designing', '2017-07-01 09:48:31'), (5, 'Rahul', 'Support', '2017-06-14 09:49:00'), (6, 'Sanjeev', 'Operations', '2017-07-01 04:49:00'); ALTER TABLE `tblemployee` ADD PRIMARY KEY (`EmpId`); ALTER TABLE `tblemployee` MODIFY `EmpId` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=7;
genratepdf.php page
<?php require_once("config.php"); require('fpdf/fpdf.php'); $pdf = new FPDF(); $pdf->AddPage(); // code for print Heading of tables $pdf->SetFont('Arial','B',12); $ret ="SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA`='empdata' AND `TABLE_NAME`='tblemployee'"; $query1 = $dbh -> 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(46,12,$column_heading,1); }} //code for print data $sql = "SELECT * from tblemployee "; $query = $dbh -> prepare($sql); $query->execute(); $results=$query->fetchAll(PDO::FETCH_OBJ); $cnt=1; if($query->rowCount() > 0) { foreach($results as $row) { $pdf->SetFont('Arial','',12); $pdf->Ln(); foreach($row as $column) $pdf->Cell(46,12,$column,1); } } $pdf->Output(); ?>Download Here