How to generate barcode in codeigniter? Create display barcode using codeigniter with zend barcode library
In this article we’ll discuss how to generate barcode in codeigniter using the zend barcode library
Download and copy zend files to application/libraries
Controller : Main.php
Create a controller Main.php and paste the below code
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Main extends CI_Controller {
public function index()
{
//I'm just using rand() function for data example
$data=[];
$code = rand(10000, 99999);
//load library
$this->load->library('zend');
//load in folder Zend
$this->zend->load('Zend/Barcode');
//generate barcode
$imageResource = Zend_Barcode::factory('code128', 'image', array('text'=>$code), array())->draw();
imagepng($imageResource, 'barcodes/'.$code.'.png');
$data['barcode'] = 'barcodes/'.$code.'.png';
$this->load->view('welcome',$data);
}
}
- Generate a random number
- load zend library
- Zend_barcode uses a factory method with five arguments which will create an instance of a renderer that extends Zend_Barcode_Renderer_Renderer Abstract. The arguments are:
- The name of barcode format (e.g., “code39”) (mandatory)
- The name of renderer (e.g., “image”) (mandatory)
- Options to pass to the barcode object (an array or Zend_Config object) (optional)
- Options to pass to the renderer object (an array or Zend_Config object) (optional)
- Boolean to indicate whether or not to automatically render errors. (optional default TRUE)
- 4. store the image in barcodes folder
- load view page with the generated image name
4. imagepng() will Output a PNG image to either the browser or a file
View :
<div>
<img src="<?php echo $barcode; ?>">
</div>
Display the returned image
Hope this tutorial to generate barcode in codeigniter will help you.