Less code = less bugs

Zend_Barcode – part 1 : using



Zend Framework 1.10 will integrate Zend_Barcode initially called Zend_Image_Barcode in the proposals.

The main difference between this first proposition and Zend_Barcode, it’s the separation between Objects and Renderers. This allowed to write an image generator (Zend_Barcode_Renderer_Image) and a PDF generator (Zend_Barcode_Renderer_Pdf).

This component internally uses a new version of Zend_Validate_Barcode specially rewritten for 1.10 by Thomas (http://www.thomasweidner.com/flatpress/2009/12/17/validating-barcodes/).

The official documentation will of course integrate the examples showing how to use the component but here is some use cases.

1. The image generator file ‘barcode.php’

You can put at the root of your Web server:

<?php
set_include_path('../library');
require_once 'Zend/Barcode.php';
Zend_Barcode::render($_GET['barcodeType'],
                     'image',
                     $_GET,
                     $_GET);

2. A call in your view and… a first error

<img src="barcode.php?barcodeType=code39" />

This will of course give you an image of error:

Because no text is provided.

3. Your first barcode

You obtain it by simply adding the ‘text’ parameter:

<img src="barcode.php?barcodeType=code39&text=ZEND-FRAMEWORK" />

You have your first barcode in 5 lines of code:

4. A better font

If you use the image renderer (based on GD extension) and if you don’t specify a TTF font, the built-in fonts will be used. You can set your own font in the options of the barcode or by global definition:

<?php
set_include_path('../library');
require_once 'Zend/Barcode.php';
Zend_Barcode::setBarcodeFont('../data/fonts/tahoma.ttf');
Zend_Barcode::render($_GET['barcodeType'], 'image', $_GET, $_GET);

You will obtain:

2 Comments

  1. Joaquin L. Robles's Gravatar Joaquin L. Robles
    1 April 2010    

    hi there, this won’t work in the MVC model…
    I have this code

    public function codigoAction()
    {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();
        Zend_Barcode::render($_GET('barcodeType'), 'image', $_GET, $_GET);
    }
    

    but would return a browser error, the image couldn’t be displayed….

  2. mikaelkael's Gravatar mikaelkael
    1 April 2010    

    I have no problem with your code, I call this url: http://localhost/index/barcode?barcodeType=code39&text=ZEND in mybrowser.
    (your code is in the IndexController) and I receive the correct image.

    If I put <img src="http://localhost/index/barcode?barcodeType=code39&text=ZEND" /> in a view, I have also the image.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>