Generate PDF File from MySQL Database Using PHP

This is another export feature php tutorials, I will create simple PHP script to fetch data from MySQL and create pdf file using php. We will use third party FPDF.The FPDF is 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 very common and popular file format to read,view and write documents.PDF format is independent of application software, hardware, and operating systems.

FPDF has following main features

There are dependency php extension which is Zlib to enable compression and GD for GIF image support. The latest version requires at least PHP 5.1.

export-pdf-mysql-php

Checkout other php export tutorials,

We will follow following steps to Generate PDF

  • Download the FPDF library from fpdf.org
  • We will featch data from MySQL database into the page.
  • We will use FPDF libs function to generate pdf file with header and footer.

Step 1: We will create employee table into mysql database.

We will generate some sample data and insert into employee table.

Step 2: Connect MySQL database with PHP. We will create connection.php file and add below code.

Above file is used to connect and select database using PHP and MySQL.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.

We will include connection and pdf libs file, for customization of 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 added below code.

We have added HTML form tag and define action value generate_pdf.php file.

Conclusion:

We have generated pdf file using php and MySQL database, You can generate pdf using other database as well.You just need to replace MySQL query string.

You can download source code and see Demo from below link.

Leave a Reply

Your email address will not be published. Required fields are marked *