Guía 4 – Crear Código de Barras

Con la publicación de la generación de QR ha surgido, a alguno de los usuarios de PHPRunner, la necesidad de disponer de código de barras de 1 dimensión, Code 128, que es el que disponen de los artículos y que las tiendas y almacenes utilizan para identificar el artículo.

Objetivo

Crear imáges de códigos de barras de 1D y almacenarlas en la gestión de ficheros que hace PHPrunner, exactamente igual que si hubieramos utilizado el aplicativo para cargarla en el sistema.

Solución

Para la creación de este tipo de imágenes he utilizado las librerias PHP de https://github.com/picqer/php-barcode-generator.

DEMO: https://fhumanes.com/barcode/

Es simple y dispone de un conjunto enorme de códigos de 1D.

En el ejemplo, tanto en el Alta como en la Edición del registro, lo que hace es crear un código de barras 1D con el contenido del campo “Text” y el tipo de gráfico elegido.

El código que hace la imagen y la guarda es:

generate_barcode.php
<?php
// https://github.com/picqer/php-barcode-generator , source of Code

/* 
Occurs after record was updated  or added

$values     - array of values has been written to the database.
              To access specific field value use $values["FieldName"]
              "dict" is an alternate name for this parameter.              
$where      - WHERE clause that points to the edited record. Example: ID=19              
$oldvalues  - array with replaced field values. To access specific column value use
              $oldvalues["FieldName"]              
$keys       - array of key column values that point to the edited record. To access
              specific key column use $keys["KeyFieldName"]              
$inline     - equals to true when the Inline Edit in process, false otherwise              
$pageObject - an object of Page class representing the current page  
*/
global $conn;
//  Barcode "type" retrieval
$id_type = $values['prueba_barcode_type_idprueba_barcode_type'];
$sql = "SELECT Type, Code FROM prueba_barcode_type WHERE idprueba_barcode_type = $id_type";
$rs = $conn->query($sql);
$data = $rs->fetch_assoc();
$type = $data['Type'];
$code = $data['Code'];

// Load the barcode library classes
require_once __DIR__ . '/php-barcode-generator_2.2.4/autoload.php'; 

// Save it to a file
$fileName = 'Barcode_'.$values['idprueba_barcode'].'.png';
$file = substr(__DIR__, 0, -6);  // root of file
$file = $file.'files/'.$fileName;

$Color = [0, 0, 0]; // Black


$generator = new Picqer\Barcode\BarcodeGeneratorPNG();

file_put_contents($file, $generator->getBarcode($values['Text'],$type, 2, 25, $Color));

/*
The getBarcode() method accepts the following parameters:

    $barcode  - String needed to encode in the barcode
    $type  - Type of barcode, use the constants defined in the class
    $widthFactor  - Width is based on the length of the data, with this factor you can make the barcode bars wider than default
    $height  - The total height of the barcode in pixels
    $foregroundColor -  Hex code as string, or array of RGB, of the colors of the bars (the foreground color)
*/

// Save the new file in Database

$size = filesize($file);
$fileArray = [];
$fileArray[0]['name']= 'files\/'.$fileName;
$fileArray[0]['usrName']= $fileName;
$fileArray[0]['size']= $size;
$fileArray[0]['type']= 'image\/png';
$fileArray[0]['searchStr'] = $fileName.',!:sStrEnd'; 
$fileFileSystem=my_json_encode($fileArray);
            
// Update in DB the file
$id_key = $values['idprueba_barcode']; 
$sql="Update prueba_barcode set File = '$fileFileSystem' where idprueba_barcode = $id_key";
$res=db_exec($sql,$conn);

Como siempre, cualquier duda me podéis contactar en [email protected]

Os dejo los ficheros que necesitaréis, si lo queréis reproducir en vuestros equipos.

Adjuntos

Archivo Tamaño de archivo Descargas
zip Backup de la Base de Datos 1 KB 506
zip PHPRunner 10.7 - Actualizado 24/07/2022 145 KB 625

Blog personal para facilitar soporte gratuito a usuarios de PHPRunner