An invoice is a commercial document given by the seller (or service provider) to the receiver detailing the transaction. It should have details about the items, quantity, amount, discount, tax, shipping, payment terms and more information.
If you are running an eCommerce store, with every purchase you should send an invoice, with an option to export as PDF will be good. It is a feature that will allow you to elevate your brand presence.
There are numerous invoice generators available for free online. When you can generate one on your own quickly, then why do you need to go elsewhere? This article will help you to generate an eCommerce purchase invoice with a sleek and clean template.
The purchase invoice generation is a part of an eCommerce application software. It’s a document or bill that confirms the transaction between the seller and the customer. It is a legal requirement in many countries.
This code will generate invoices in PDF format. We have already seen how to generate PDF using PHP script.
This example shows the purchase order list on a landing page. This order data is dynamic from the database.
It has the purchase data with the HTML control to trigger invoice generation.
The output invoice document created by this example is in PDF format. It uses the TCPDF PHP library to generate PDF.
Download TCPDF and put it into the application folder. Specify the path of the TCPDF class file in the PDFService.php
A PDF generation code creates a PDF document write handler. It sets the document header, title, body content and more.
It prepares HTML for the body content of the invoice to be generated. This HTML embeds the purchase data from the database.
This is the HTML code for the landing page to display the purchase order list.
This order list displays row-wise purchase data like product name, amount, purchase date and more.
It contains the invoice generation link in each row. On clicking this link the purchase invoice PDF will open in a new tab.
The order details are from the database. It uses a unique identifier as the reference for each purchase.
index.php
<?php
use Phppot\Order;
require_once __DIR__ . '/Model/Order.php';
$orderModel = new Order();
$orderResult = $orderModel->getAllOrders();
?>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>CSRF Protection using PHP</title>
<link rel="stylesheet" type="text/css"
href="assets/css/style.css" />
</head>
<body>
<div class="phppot-container">
<h1 class="page-heading">Generate PDF invoice with FPDF</h1>
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">Order Ref</th>
<th scope="col" class="text-right">Amount</th>
<th scope="col" class="text-right">Order Status</th>
<th scope="col" class="text-right">Invoice</th>
</tr>
</thead>
<tbody>
<?php foreach ($orderResult as $k => $v) { ?>
<tr>
<td><?php echo $orderResult[$k]["order_ref"];?></td>
<td class="text-right"><?php echo $orderResult[$k]["amount"];?></td>
<td class="text-right"><?php echo $orderResult[$k]["order_status"];?></td>
<td class="text-right"><a target="_blank"
title="Generate Invoice"
href="./invoice.php?id=<?php echo $orderResult[$k]["id"];?>"><?php echo $orderResult[$k]["order_invoice"];?></a></td>
</tr>
<?php }?>
</tbody>
</table>
</div>
</body>
</html>
On clicking the invoice generation link, the PHP code integrate eCommerce purchase invoice PDF.
This code shows the HTML template for generating the PDF.
Template/purchase-invoice-template.php
<?php
use Phppot\Order;
require_once __DIR__ . '/../Model/Order.php';
function getHTMLPurchaseDataToPDF($result, $orderItemResult, $orderedDate, $due_date)
{
ob_start();
?>
<html>
<head>Receipt of Purchase - <?php echo $result[0]["order_invoice"]; ?>
</head>
<body>
<div style="text-align:right;">
<b>Sender:</b> Phppot
</div>
<div style="text-align: left;border-top:1px solid #000;">
<div style="font-size: 24px;color: #666;">INVOICE</div>
</div>
<table style="line-height: 1.5;">
<tr><td><b>Invoice:</b> #<?php echo $result[0]["order_invoice"]; ?>
</td>
<td style="text-align:right;"><b>Receiver:</b></td>
</tr>
<tr>
<td><b>Date:</b> <?php echo $orderedDate; ?></td>
<td style="text-align:right;"><?php echo $result[0]["customer_first_name"] . ' ' . $result[0]["customer_last_name"]; ?></td>
</tr>
<tr>
<td><b>Payment Due:</b><?php echo $due_date; ?>
</td>
<td style="text-align:right;"><?php echo $result[0]["customer_company"]; ?></td>
</tr>
<tr>
<td></td>
<td style="text-align:right;"><?php echo $result[0]["customer_address"]; ?></td>
</tr>
</table>
<div></div>
<div style="border-bottom:1px solid #000;">
<table style="line-height: 2;">
<tr style="font-weight: bold;border:1px solid #cccccc;background-color:#f2f2f2;">
<td style="border:1px solid #cccccc;width:200px;">Item Description</td>
<td style = "text-align:right;border:1px solid #cccccc;width:85px">Price ($)</td>
<td style = "text-align:right;border:1px solid #cccccc;width:75px;">Quantity</td>
<td style = "text-align:right;border:1px solid #cccccc;">Subtotal ($)</td>
</tr>
<?php
$total = 0;
$productModel = new Order();
foreach ($orderItemResult as $k => $v) {
$price = $orderItemResult[$k]["item_price"] * $orderItemResult[$k]["quantity"];
$total += $price;
$productResult = $productModel->getProduct($orderItemResult[$k]["product_id"]);
?>
<tr> <td style="border:1px solid #cccccc;"><?php echo $productResult[0]["product_title"]; ?></td>
<td style = "text-align:right; border:1px solid #cccccc;"><?php echo number_format($orderItemResult[$k]["item_price"], 2); ?></td>
<td style = "text-align:right; border:1px solid #cccccc;"><?php echo $orderItemResult[$k]["quantity"]; ?></td>
<td style = "text-align:right; border:1px solid #cccccc;"><?php echo number_format($price, 2); ?></td>
</tr>
<?php
}
?>
<tr style = "font-weight: bold;">
<td></td><td></td>
<td style = "text-align:right;">Total ($)</td>
<td style = "text-align:right;"><?php echo number_format($total, 2); ?></td>
</tr>
</table></div>
<p><u>Kindly make your payment to</u>:<br/>
Bank: American Bank of Commerce<br/>
A/C: 05346346543634563423<br/>
BIC: 23141434<br/>
</p>
<p><i>Note: Please send a remittance advice by email to vincy@phppot.com</i></p>
</body>
</html>
<?php
return ob_get_clean();
}
?>
On the server-side, the PHP code in the invoice.php file fetches the purchase order data from the database.
The database related operations are in the application DataSource class.
After fetching the results, this code invokes the invoice generation function. This function accepts the dynamic data as its argument. In a previous article, we have seen how to write MySQL data into a PDF document.
The invoice template shows the invoice number, date and due. Also, it displays the list of purchased items and customer details.
invoice.php
<?php
use Phppot\Order;
require_once __DIR__ . '/Model/Order.php';
$orderModel = new Order();
$result = $orderModel->getPdfGenerateValues($_GET["id"]);
$orderItemResult = $orderModel->getOrderItems($result[0]["id"]);
if (! empty($result)) {
require_once __DIR__ . "/lib/PDFService.php";
$pdfService = new PDFService();
$pdfService->generatePDF($result, $orderItemResult);
}
lib/PDFService.php
<?php
use Phppot\Config;
ini_set('display_errors', 'On');
error_reporting(E_ALL);
require_once __DIR__ . '/../lib/Config.php';
$config = new Config();
class PDFService {
function generatePDF($result, $orderItemResult) {
require_once __DIR__ . '/../vendor/tcpdf/tcpdf.php';
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
$pdf->SetHeaderData('', PDF_HEADER_LOGO_WIDTH, '', '', array(
0,
0,
0
), array(
255,
255,
255
));
$pdf->SetTitle('Invoice - ' . $result[0]["order_invoice"]);
$pdf->SetMargins(20, 10, 20, true);
if (@file_exists(dirname(__FILE__) . '/lang/eng.php')) {
require_once (dirname(__FILE__) . '/lang/eng.php');
$pdf->setLanguageArray($l);
}
$pdf->SetFont('helvetica', '', 11);
$pdf->AddPage();
$orderedDate = date('d F Y', strtotime($result[0]["order_at"]));
$due_date = date("d F Y", strtotime('+' . Config::TERMS . 'days', strtotime($orderedDate)));
require_once __DIR__ . '/../Template/purchase-invoice-template.php';
$html = getHTMLPurchaseDataToPDF($result, $orderItemResult, $orderedDate, $due_date);
$filename = "Invoice-" . $result[0]["order_invoice"];
$pdf->writeHTML($html, true, false, true, false, '');
ob_end_clean();
$pdf->Output($filename . '.pdf', 'I');
}
}
?>
This database script has the data for the purchase order and product tables. Import this script to run this program in your environment.
sql/database.sql
-- --------------------------------------------------------
--
-- Table structure for table `tbl_order`
--
CREATE TABLE `tbl_order` (
`id` int(11) NOT NULL,
`order_ref` varchar(255) NOT NULL,
`order_invoice` int(11) NOT NULL,
`customer_first_name` varchar(255) NOT NULL,
`customer_last_name` varchar(255) NOT NULL,
`customer_address` varchar(255) NOT NULL,
`customer_company` varchar(255) NOT NULL,
`amount` decimal(10,2) NOT NULL,
`order_status` varchar(100) NOT NULL,
`order_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `tbl_order`
--
INSERT INTO `tbl_order` (`id`, `order_ref`, `order_invoice`, `customer_first_name`, `customer_last_name`, `customer_address`, `customer_company`, `amount`, `order_status`, `order_at`) VALUES
(1, '1iRxJtOtAlai4v6LEuGI', 786567, 'David', 'Richard', 'United States', 'Cloud Technologies', '3300.00', 'Completed', '2021-01-12 09:51:38'),
(2, '1iRxJtOtAlai4v6LEuGR', 486231, 'William', 'George', 'United States', 'Smart Tech Info', '500.00', 'Completed', '2021-01-12 09:38:27');
-- --------------------------------------------------------
--
-- Table structure for table `tbl_order_items`
--
CREATE TABLE `tbl_order_items` (
`id` int(11) NOT NULL,
`order_id` int(10) UNSIGNED NOT NULL,
`product_id` int(11) NOT NULL,
`item_price` decimal(10,2) NOT NULL,
`quantity` int(10) UNSIGNED NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `tbl_order_items`
--
INSERT INTO `tbl_order_items` (`id`, `order_id`, `product_id`, `item_price`, `quantity`) VALUES
(1, 1, 1, '1500.00', 2),
(2, 1, 2, '300.00', 1),
(6, 2, 3, '500.00', 1);
-- --------------------------------------------------------
--
-- Table structure for table `tbl_product`
--
CREATE TABLE `tbl_product` (
`id` int(11) NOT NULL,
`product_title` varchar(255) NOT NULL,
`price` decimal(10,2) NOT NULL,
`create_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `tbl_product`
--
INSERT INTO `tbl_product` (`id`, `product_title`, `price`, `create_at`) VALUES
(1, 'FinePix Pro2 3D Camera', '1500.00', '2021-01-11 13:00:22'),
(2, 'Luxury Ultra thin Wrist Watch', '300.00', '2021-01-11 13:00:34'),
(3, 'Luxury Tv', '500.00', '2021-01-11 13:00:34');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `tbl_order`
--
ALTER TABLE `tbl_order`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `tbl_order_items`
--
ALTER TABLE `tbl_order_items`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `tbl_product`
--
ALTER TABLE `tbl_product`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `tbl_order`
--
ALTER TABLE `tbl_order`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT for table `tbl_order_items`
--
ALTER TABLE `tbl_order_items`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
--
-- AUTO_INCREMENT for table `tbl_product`
--
ALTER TABLE `tbl_product`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=31;
This section shows the output screenshots of this example.
The following screenshot shows the landing page view that displays the purchase order list.
This output shows the eCommerce purchase invoice PDF document screenshot below.
In this article, we have created a simple example to generate an eCommerce purchase invoice in PDF format.
We have seen how to integrate the PHP PDF library to run this example.
This code used a database as a source to generate PDF with dynamic data. It will be helpful to use this code in your application by changing the target database. It needs only minor adjustments in the code in such cases.
This document can be enhanced further with more details. Example: Billing, Shipping details and more.
I hope, this will be a good start to help you prepare the purchase invoice PDF programmatically.
Been your follower and this is quite interesting. Good initiative. Happy programming. Thanks
Welcome Kayode. Thank you so much for your support.
thank you so mutch i m redouane from morroco i m teatcher
Welcome Redouane.
Thanks for your help
Welcome Nikwo.
The version I downloaded does not have a tcpdf.php file located in Vendor folder. So most of the code is working but fatal error when I hit this.
It’s available on github, a small Google search will help. Let me know if you couldn’t get it.
Ah! found it on git hub! Awesome Script!
Thank you Bryan.
Ma’am i like your awesome trick, please share with fixed header and footer with page number
Hi Nausher,
Thank you. Sure I will try to rollout that also soon.
Thank you, made creating an invoice very easy with a few modifications for my data. Is there a way to automatically attach and send the pdf via email?
Hi Skot,
Welcome. I can do it as a service for you, let me know.