This is another php pdf export feature tutorials, I will create simple PHP script to fetch data from MySQL and create pdf file using php. We will use third party PHP FPDF library. 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
- Choice of measure unit, page format and margins.
- Page header and footer management.
- Automatic page and line break with text justification
- Image support (JPEG, PNG and GIF).
- Colors
- Links
- TrueType, Type1 and encoding support
- Page compression
We Will Follow Following Steps To Generate PDF
- Download the FPDF library from fpdf.org
- We will fetch 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: Let’s connect MySQL database with PHP. We will create connection.php
file and add below code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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; } } |
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.
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 create connection with other type database.