DEV Community

Lalit Kumar
Lalit Kumar

Posted on

How to generate pdf file from dynamic data coming from MySQL database in PHP

We can generate the pdf form MySQL database by using FPDF which allows generating the pdf files without using any library. We can generate by considering the following steps;

  • Download the FPDF library from fpdf.org.
  • Generate the database teacher in the MySQL database.
  • Connect to the database by using the connection.php file.

Connection.php

Class dbObj{

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());

if (mysqli_connect_errno()) {

printf("Connect failed: %s\n", mysqli_connect_error());

exit();

} else {

$this->conn = $con;

}

return $this->conn;

}

}
Enter fullscreen mode Exit fullscreen mode

Index.php:

Now generate the index.php file which will generate the invoice of that number.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>PDF file</title>

</head>

<body>

<h2>Generate PDF</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>


</body>

</html>
Enter fullscreen mode Exit fullscreen mode

Generate_pdf.php:

Now we will create the generate_pdf.php file

<?php
include_once("connection.php");

include_once('libs/fpdf.php');

class PDF extends FPDF

{

function Header()

{

    $this->Image('logo.png',10,-1,70);

    $this->SetFont('Arial','B',13);

    $this->Cell(80);

    $this->Cell(80,10,'Employee List',1,0,'C');

}
function Footer()

{
   $this->SetY(-15);

    $this->SetFont('Arial','I',8);
    $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();
$pdf->AddPage();
$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();

?>
Enter fullscreen mode Exit fullscreen mode

Read more in original post

Top comments (0)