How to create PDF file

Project : in this project we will learn how to create pdf file and insert data in database, save pdf file in invoices folder.

FPDF Library : We have to add fpdf library in this project to generate pdf file.

fpdf folder that is pdf genertor from fpdf.org which is free source library.

We will use fpdf generator library to generate pdf file which is free source library.

You can download fpdf library, the link is given below.

Download FPDF Generator.


invoices (folder)

In this folder all the pdf file will be saved inside invoices folder after form submit
PHP
HTML FORM on (index.php)
PHP

Index

myproject/index.php
index.php
                            
                              <?php include("generate.php"); ?>
                                <!DOCTYPE html>
                                <html>
                                <head>
                                  <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
                                  <title>Codetechinfo </title>
                                </head>
                                <body>
                                  <div class="container w-75"><br>
                                    <div class="text-center w-75"> <?php echo $success; ?> <?php echo $error; ?> </div>
                                    <form method="POST" action="index.php"  class="border w-75 p-3" style="background: #f5f6fa;">
                                        <h4 class="rounded bg-primary w-100 p-2 text-white text-center">Submit and Generate PDF Invoice</h4>
                                          <div class="form-group row">
                                              <div class="col-md-6">
                                                  <label for="order_date">Date</label>
                                                  <input type="text" class="form-control" value="<?php echo date('d-m-yy'); ?>" name="order_date" id="order_date" Readonly>
                                              </div>
                                              <div class="col-md-6">
                                                  <label for="name">Customer Name</label>
                                                  <input type="text" class="form-control"  name="name" id="name">
                                              </div>
                                          </div>
                                            <div class="form-group row">
                                              <div class="col-md-6">
                                                  <label for="address">Address</label>
                                                  <input type="text" class="form-control"  name="address" id="address">
                                              </div>
                                              <div class="col-md-6">
                                                  <label for="product_name">Product Name</label>
                                                  <input type="text" class="form-control"  name="product_name" id="product_name">
                                              </div>
                                            </div>
                                            <div class="form-group row">
                                              <div class="col-md-6">
                                                  <label for="quantity">Quantity</label>
                                                  <input type="text" class="form-control" name="quantity" id="quantity">
                                              </div>
                                              <div class="col-md-6">
                                                  <label for="price">Product Price</label>
                                                  <input type="text" class="form-control"  name="price" id="price">
                                              </div>
                                            </div>
                                            <div class="form-group row">
                                              <div class="col-md-6">
                                                  <label for="gst">GST Rate(%)</label>
                                                  <input type="text" class="form-control" name="gst" id="gst">
                                              </div>
                                              <div class="col-md-6">
                                                  <label for="discount">Discount</label>
                                                  <input type="text" class="form-control" name="discount" id="discount">
                                              </div>
                                            </div>
                                            <div class="form-group row">
                                              <div class="col-md-6">
                                                  <label for="paid">Paid Amount</label>
                                                  <input type="text" class="form-control" name="paid" id="paid">
                                              </div>
                                              <div class="col-md-6">
                                                  <label for="method">Payment Method</label>
                                                  <select name="method" id="method" class="form-control">
                                                     <option value="Cash">Cash</option>
                                                     <option value="Debit Card">Debit Card</option>
                                                     <option value="Credit Card">Credit Card</option>
                                                     <option value="Cheque">Cheque</option>
                                                     <option value="Bank Transfer">Bank Transfer</option>
                                                  </select>
                                              </div>
                                            </div>
                                            <div class="form-group text-white pb-2">
                                              <input type="submit" name="submit" value="Submit & Print Invoice PDF" class="btn btn-success"> 
                                              <a href="index.php" class="btn btn-danger float-right">Close</a>
                                            </div>
                                        </form>
                                  </div><br>
                                </body>
                                </html>
                            
                          

Database and table

Database-> dbdemo Table-> invoices

Create database and table

Table in database
                                
                                  -- Table structure for table `invoices`
                                  CREATE TABLE `invoices`(
                                    `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
                                    `customer_name` varchar(100) NOT NULL,
                                    `address` varchar(100) NOT NULL,
                                    `product_name` varchar(100) NOT NULL,
                                    `quantity` int(11) NOT NULL,
                                    `price` double NOT NULL,
                                    `gst` double NOT NULL,
                                    `discount` double NOT NULL,
                                    `paid` double NOT NULL,
                                    `due` double NOT NULL,
                                    `net_total` double NOT NULL,
                                    `method` varchar(255) NOT NULL
                                  );
                                
                            
Create connection with database
myproject/dbcon.php
dbcon.php
    
        $dbhost ="localhost";
        $dbuser ="root";
        $dbpswd ="";
        $dbname ="dbdemo";
        $dbcon= mysqli_connect($dbhost,$dbuser,$dbpswd,$dbname);
        if($dbcon){
            //echo "Connected............!!!";
            return $dbcon;
            exit();
        }else{
            die("Connection failed ? ? ?". mysqli_error($dbcon));
        }
        mysqli_close($dbcon);
    

Generate PDF

Process to insert data in database table and auto genarate pdf file after form submit
myproject/generate.php
                              
                                <?
                                php include("dbcon.php"); //This is database connection file
                                include("fpdf/fpdf.php");
                                $error=''; $success='';
                                //print_r($_POST);
                                if(isset($_POST['submit'])){
                                    if(empty($_POST['name']) || empty($_POST['address']) || empty($_POST['product_name']) || empty($_POST['quantity']) || empty($_POST['price']) || empty($_POST['gst']) || empty($_POST['discount']) || empty($_POST['paid']) || empty($_POST['method'])){
                                        $error ="<div class='alert alert-danger'>All the fields are requierd ?</div>";
                                    }else if (!preg_match("/^[a-zA-Z ]+$/", $_POST['name'])){
                                        $error ="<div class='alert alert-danger'>Only alphabets are allowed !!</div>";
                                    }else if(strlen($_POST['name'])<3){
                                        $error ="<div class='alert alert-danger'>The name must be minimum 3 characters !!</div>";
                                    }else if(strlen($_POST['address'])<3){
                                        $error ="<div class='alert alert-danger'>The address  must be minimum 3 characters !!</div>";
                                    }else if(!preg_match("/^[a-zA-Z- ]+$/", $_POST['product_name'])){
                                        $error ="<div class='alert alert-danger'>Only alphabets are allowed !!</div>";
                                    }else if (strlen($_POST['product_name'])<3){
                                        $error ="<div class='alert alert-danger'>The product name must be minimum 3 characters !!</div>";
                                    }else if (!preg_match("/^[0-9]+$/", $_POST['quantity'])){
                                        $error ="<div class='alert alert-danger'>The quantity must be number !!</div>";
                                    }else if (!preg_match("/^[0-9]+$/", $_POST['price'])){
                                        $error ="<div class='alert alert-danger'>The quantity must be number !!</div>";
                                    }else if (!preg_match("/^[0-9]+$/", $_POST['gst'])){
                                        $error ="<div class='alert alert-danger'>The quantity must be number !!</div>";
                                    }else if (!preg_match("/^[0-9]+$/", $_POST['discount'])){
                                        $error ="<div class='alert alert-danger'>The quantity must be number !!</div>";
                                    }else if (!preg_match("/^[0-9]+$/", $_POST['paid'])){
                                        $error ="<div class='alert alert-danger'>The quantity must be number !!</div>";
                                    }else{
                                      $total = $_POST['price']*$_POST['quantity'];
                                      $gst = $_POST['price']*$_POST['quantity']*$_POST['gst']/100;
                                      $sub_total = $total+$gst;
                  
                                      if(!empty($_POST['discount'])){
                                        $net_total = ceil($sub_total-$_POST['discount']);
                                      }else{
                                        $net_total = 0;
                                      }
                                      if(!empty($_POST['paid'])){
                                        $due = ceil($net_total-$_POST['paid']);
                                      }else{
                                        $due = 0;
                                      }
                                      $query = "INSERT INTO invoices(order_date,customer_name,address,product_name,quantity,price,gst,discount,paid,net_total,due,method) VALUES ('".$_POST['order_date']."','".$_POST['name']."','".$_POST['address']."','".$_POST['product_name']."','".$_POST['quantity']."','".$_POST['price']."','".$_POST['gst']."','".$_POST['discount']."','".$_POST['paid']."','$net_total','$due','".$_POST['method']."')";
                                      $run = mysqli_query($dbcon,$query);
                                      if($run){
                                        $success="<div class='alert alert-success w-100'>The product and been added and created PDF invoice Please check your invoices folder !</div>";
                                        $invoice_id = mysqli_insert_id($dbcon);
                                        $pdf = new FPDF();
                                        $pdf->AddPage();
                                        $pdf->Rect(5, 5, 200, 287, 'D'); //For A4
                                        $pdf->SetFont("Arial","B", 16);
                                        $pdf->Cell(65,15,"MY COMPANY",1,1,"C");
                                        $pdf->SetFont("Arial",null,12);
                                        $pdf->SetFont("Arial","B", 12);
                                        $pdf->Cell(35,8,"Customer Name: ",0,0);
                                        $pdf->SetFont("Arial","", 12);
                                        $pdf->Cell(52,8, ucwords($_POST['name']),0,1);
                                        $pdf->Cell(35,8,"Address: ".ucwords($_POST['address']), 0, 1);
                                        $pdf->SetFont("Arial","", 12);
                                        $pdf->Cell(35,8,"GST No: 0000DSFFGGFD09",0,0);
                                        $pdf->SetY(25);
                                        $pdf->Cell(168,9,"Order Date  :",0,0,"R");
                                        $pdf->Cell(23,9,$_POST['order_date'],0,1,"R");
                                        $pdf->Cell(168,9,"Invoice No. :",0,0,"R");

                                        $pdf->Cell(18,9,"SIN/".$invoice_id,0,1,"R");

                                        $pdf->SetY(49);
                                        $pdf->SetFont("Arial","B", 12);
                                        $pdf->Cell(50,8,"",0,1);
                                        $pdf->Cell(10,8," S.N. ",1,0,"C");
                                        $pdf->Cell(100,8,"Services/Product Name",1,0,"C");
                                        $pdf->Cell(25,8,"Quantity",1,0,"C");
                                        $pdf->Cell(25,8,"Price (Rs)",1,0,"C");
                                        $pdf->Cell(30,8,"Total (Rs)",1,1,"C");
                                        $pdf->SetFont("Arial","", 12);

                                        $pdf->Cell(10,7,'1',1,0,"C");
                                        $pdf->Cell(100,7,ucwords($_POST['product_name']),1,0,"L");
                                        $pdf->Cell(25,7, $_POST['quantity'],1,0,"C");
                                        $pdf->Cell(25,7, $_POST['price'].".00",1,0,"R");
                                        $pdf->Cell(30,7, $total.".00",1,1,"R");

                                        $pdf->SetY(65);  //box
                                        $pdf->Cell(160,145," ",1,0);
                                        $pdf->Cell(30,145," ",1,0);
                                        $pdf->SetY(202);
                                        $pdf->SetFont("Arial","B", 12);
                                        $pdf->Cell(160,8,"Sub Total",1,0,"R");
                                        $pdf->Cell(30,8,$total.".00",1,0,"R");
                                        
                                        $pdf->SetY(210);
                                        $pdf->Cell(110);
                                        $pdf->SetFont("Arial","", 12);
                                        $pdf->Cell(50,8,"GST Tax ",1,0,"R");
                                        $pdf->SetFont("Arial","B", 12);
                                        $pdf->Cell(30,8,ceil($gst).".00",1,1,"R");
                                        $pdf->Cell(110);
                                        $pdf->SetFont("Arial","", 12);
                                        $pdf->Cell(50,8,"Discount ",1,0,"R");
                                        $pdf->SetFont("Arial","B", 12);
                                        $pdf->Cell(30,8,$_POST['discount'].".00",1,1,"R");
                                        $pdf->Cell(110);
                                        $pdf->SetFont("Arial","", 12);
                                        $pdf->Cell(50,8,"Net Total ",1,0,"R");
                                        $pdf->SetFont("Arial","B", 12);
                                        $pdf->Cell(30,8,$net_total.".00",1,1,"R");
                                        $pdf->Cell(110);
                                        $pdf->SetFont("Arial","", 12);
                                        $pdf->Cell(50,8,"Paid Amount ",1,0,"R");
                                        $pdf->SetFont("Arial","B", 12);
                                        $pdf->Cell(30,8,$_POST['paid'].".00",1,1,"R");
                                        $pdf->Cell(110);
                                        $pdf->SetFont("Arial","", 12);
                                        $pdf->Cell(50,8,"Due Amount ",1,0,"R");
                                        $pdf->SetFont("Arial","B", 12);
                                        $pdf->Cell(30,8,$due.".00",1,1,"R");
                                        $pdf->Cell(110);
                                        $pdf->SetFont("Arial","", 12);
                                        $pdf->Cell(50,8,"Payment Method ",1,0,"R");
                                        $pdf->SetFont("Arial","B", 12);
                                        $pdf->Cell(30,8,$_POST['method'],1,1,"R");
                                        $pdf->SetY(210);
                                        $pdf->SetFont("Arial","", 12);
                                        $pdf->Cell(110,8,"Bank Details",1,0,"L");
                                        $pdf->SetY(218);
                                        $pdf->Cell(110,8,"Bank Name:",1,1,"L");
                                        $pdf->SetY(226);
                                        $pdf->Cell(110,8,"Bank A/C:",1,1,"L");
                                        $pdf->SetY(234);
                                        $pdf->Cell(110,8,"IFSC Code:",1,1,"L");

                                        $pdf->SetY(255);
                                        $pdf->SetFont("Arial","B");
                                        $pdf->Cell(175,15,"for CODEONSATEN.COM",0,1,"R");
                                        $pdf->SetFont("Arial","", 12);
                                        $pdf->SetY(270);
                                        $pdf->Cell(180,5,"------------------------------------------",0,1,"R");
                                        $pdf->Cell(180,1,"Authorized Signature",0,1,"R");
                                        $invoice = $pdf->Output("invoices/".$_POST['name'].".pdf","F");
                                        if($invoice){
                                            $_POST['order_date']='';$_POST['name']='';$_POST['address']='';$_POST['product_name']='';$_POST['quantity']='';
                                            $_POST['price']='';$_POST['gst']='';$_POST['discount']='';$_POST['paid']='';$net_total='';$due='';$_POST['method']='';
                                          }
                                      }else{
                                        $error="<div class='alert alert-danger w-100'>Failed to add products and create pdf invoice  !</div>";  
                                      }
                                    }
                                }else{
                                  return false;
                                }
                              
                          

Generated PDF File

Check the folder in which folder pdf file has been save

PHP

css folder

You must download and include bootstrap css source files for good interface OR You can add cdn link from bootstrap website.
myproject/css
bootstrap.min.css