This PHP tutorial helps to create barcode using PHP and generate pdf file. There are a lot of PHP barcode libs available but I am using a simple and lightweight library.
Barcode is an optical, machine-readable, representation of data; the data usually describes something about the object that carries the barcode. The barcodes systematically represented data by varying the widths and spacings of parallel lines.
The Barcodes can be scanned by special optical scanners called barcode readers or application software became available for devices that could read images using smartphone cameras.
To generate a pdf file of barcode, I am using mPDF libs, You can read more about mPDF library from my previous tutorial How to Create PDF file Using mpdf and PHP. The mpdf libs is an awesome package to generate a pdf file with many options, The mPDf
help to convert text into rich UI pdf format using PHP.
There are a lot of places where you can see the uses of barcode, The e-commerce company/many product companies use barcodes to track products. The barcode is also available in their Invoice Bill.
There are the following dependency libs in this tutorial,
- barcode libs to generate barcode using PHP, You can download them from here.
- mPDF libs to generate PDF file using PHP, You can download from here.
We will download and include the above libs into index.php
file, I am using composer to download mPDF libs, You can download using 'composer require mpdf/mpdf'
command.
Barcode PHP libs supported the following types of barcode formats,
- Code 128
- Code 39
- Code 2of5
- Codabar
Normally barcode is generated in a horizontal manner but this lib gave functionality to generate barcode vertically.
PHP Script to Generate Barcode and Print Into PDF
We will load mpdf libs at the top of the file, We will create a barcode HTML string and send them to mpdf libs to render HTML code into a pdf file.
<?php require_once __DIR__ . '/vendor/autoload.php'; $product_code_39 = "<img alt='code 39 bar code' src='barcode.php?codetype=Code39&size=60&text=productNo-324324&print=true' />"; $product_code_128 = "<img src="barcode.php?codetype=Code128&size=60&text=item-no-234234234&print=true" alt="128 bar code">"; $product_code_128_vertical = "<img src="barcode.php?codetype=Code128&size=160&text=sku-F34D&print=true&orientation=vertical" alt="128 bar code">"; $sku_code = "<img src="barcode.php?text=SKU:-V45FR32&print=true&size=50" alt="sample code">"; $html = ''; $html = $product_code_39 .' '. $product_code_128 .' '. $sku_code.' '. $product_code_128_vertical; generatePdf($html); function generatePdf($html) { $mpdf = new mPDF(); $mpdf->WriteHTML($html); //save the file put which location you need folder/filname $mpdf->Output("phpflow.pdf", 'F'); //out put in browser below output function $mpdf->Output(); } ?>
Hi, Really great effort. Everyone must read this article. Thanks for sharing.
Sorry at the moment there is no link to barcode libs
https://github.com/mpdf/mpdf