This is another PHP pdf export feature tutorial, I will create a simple PHP script to fetch data from MySQL and create a pdf file using PHP. We will use third-party PHP FPDF library.
The FPDF is a very awesome PHP class to generate PDF using PHP from MySQL database. This is open source PHP library to generate pdf file using PHP.
PDF is a very common and popular file format to read, view, and write documents.PDF format is independent of application software, hardware, and operating systems.
If you are more comfortable in watching a video that explains about using pdf generation, then you should watch this video tutorial.
There is one dependency php extension which is Zlib to enable compression and GD for GIF image support. The latest version requires at least PHP 5.1.
Checkout other php export tutorials,
Step 1: We will create employee table into MySQL database.
-- -- Table structure for table `employee` -- CREATE TABLE IF NOT EXISTS `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', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='datatable demo table' AUTO_INCREMENT=64 ;
We will generate some sample data and insert it into the employee table.
-- -- 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), (11, 'Jena Gaines', 90560, 30), (12, 'Quinn Flynn', 342000, 22), (13, 'Charde Marshall', 470600, 36), (14, 'Haley Kennedy', 313500, 43), (15, 'Tatyana Fitzpatrick', 385750, 19), (16, 'Michael Silva', 198500, 66);
Step 2: Let’s connect MySQL database with PHP. We will create connection.php
file and add below code.
Class dbObj{ /* Database connection start */var $dbhost = "localhost"; var $username = "root"; var $password = ""; var $dbname = "test"; var $conn; function getConnstring() { $con = mysqli_connect($this->dbhost, $this->username, $this->password, $this->dbname) or die("Connection failed: " . mysqli_connect_error()); /* check connection */if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } else { $this->conn = $con; } return $this->conn; } }
The above file is used to connect and select MySQL database using PHP. You need to change $dbhost, $username, $password, and $dbname variable’s value with your database credentials.
Step 3: We will create generate_pdf.php
file and add below code.
Image('logo.png',10,-1,70); $this->SetFont('Arial','B',13); // Move to the right $this->Cell(80); // Title $this->Cell(80,10,'Employee List',1,0,'C'); // Line break $this->Ln(20); } // Page footer function Footer() { // Position at 1.5 cm from bottom $this->SetY(-15); // Arial italic 8 $this->SetFont('Arial','I',8); // Page number $this->Cell(0,10,'Page '.$this->PageNo().'/{nb}',0,0,'C'); } } $db = new dbObj(); $connString = $db->getConnstring(); $display_heading = array('id'=>'ID', 'employee_name'=> 'Name', 'employee_age'=> 'Age','employee_salary'=> 'Salary',); $result = mysqli_query($connString, "SELECT id, employee_name, employee_age, employee_salary FROM employee") or die("database error:". mysqli_error($connString)); $header = mysqli_query($connString, "SHOW columns FROM employee"); $pdf = new PDF(); //header $pdf->AddPage(); //foter page $pdf->AliasNbPages(); $pdf->SetFont('Arial','B',12); foreach($header as $heading) { $pdf->Cell(40,12,$display_heading[$heading['Field']],1); } foreach($result as $row) { $pdf->Ln(); foreach($row as $column) $pdf->Cell(40,12,$column,1); } $pdf->Output(); ?>
We will include connection and pdf libs file, for customization of the header and footer of pdf files, we will override header and footer methods and define our CSS design.
Step 4: We will create index.php
file and add the below code.
<meta charset="UTF-8"> <title>Simple Example of PDF file using PHP and MySQL</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <div class="container" style="padding-top:50px"> <h2>Generate PDF file from MySQL Using PHP</h2> <form class="form-inline" method="post" action="generate_pdf.php"> <button type="submit" id="pdf" name="generate_pdf" class="btn btn-primary"><i class="fa fa-pdf" "="" aria-hidden="true"></i> Generate PDF</button> </form> </div>
We have added an HTML form tag and defined the action value generate_pdf.php
file.
We have generated pdf file using PHP and MySQL database, You can generate pdf using another database as well. You just need to create connections with other types of databases.
You can download the source code and see Demo from the below link.
This tutorial helps integrate a PHP SDK with Laravel. We'll install aws-php-sdk into laravel application and access all aws services… Read More
in this quick PHP tutorial, We'll discuss php_eol with examples. PHP_EOL is a predefined constant in PHP and represents an… Read More
This Laravel tutorial helps to understand table Relationships using Elequonte ORM. We'll explore laravel table Relationships usage and best practices… Read More
We'll explore different join methods of Laravel eloquent with examples. The join helps to fetch the data from multiple database… Read More
in this Laravel tutorial, We'll explore valet, which is a development environment for macOS minimalists. It's a lightweight Laravel development… Read More
I'll go through how to use soft delete in Laravel 10 in this post. The soft deletes are a method… Read More
View Comments
link has been given in tuts, http://www.fpdf.org/
I can't trace the error.......Warning: Invalid argument supplied for foreach() in C:wampwwwPhpbintermgenerate_pdf.php on line 60
may be foreach params is not array type
page downloading directly, not shown. what can I do?
may be header not set
Thank you for your interest. but unfortunately it did not. downloading without displaying the page
i sent u mail with code
yes, you can try width using Cell() method
sir ,
what is 'Field' in 48th line of generate_pdf.php?
i need explanation.
passing pdf column value like, width, colvalue etc
have u downloaded and stored lib into libs/fpdf.php location.
Where is fpdf file
in the root of the project folder
hello tnxs a lot worked for me but i want to export image from db
but image is stored in the folder not in db (only url is stored in the db)
how can i export the image ?
there is image() method that takes image path as a argument,You can get more information from fpdf official docs.
$pdf->Image('image_path',x1,y1,width,height);
x1 - space from left side
y1 - top space
width - image width
height - image height
Note - x1, y1, width, height values must be in integer values (value without decimal point)
dbhost, $this->username, $this->password, $this->dbname) or die("Connection failed: " . mysqli_connect_error()); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } else { $this->conn = $con; } return $this->conn; } } ?>
Fatal error: Uncaught Error: Class 'dbObj' not found in C:\xampp\htdocs\generate_pdf.php:34 Stack trace: #0 {main} thrown in C:\xampp\htdocs\generate_pdf.php on line 34
i got this error
have you created connection.php file and imported into index.php file
I am getting this below error,could anyone please help me out with solution for this.
Fatal error: Uncaught Exception: FPDF error: Some data has already been output, can't send PDF file in D:\XAMPP\htdocs\pdfdemo\libs\fpdf.php:271 Stack trace: #0
Works perfectly for me. Thank you for this.
Just need one more help, how can I specify the text wrap in the column?
need to read doc fpdf.