Barcode generator in PHP that is easy to use, non-bloated and framework independent.

Last update: May 26, 2022

PHP Barcode Generator

Build Status Github Actions Total Downloads

This is an easy to use, non-bloated, framework independent, barcode generator in PHP.

It creates SVG, PNG, JPG and HTML images, from the most used 1D barcode standards.

The codebase is based on the TCPDF barcode generator by Nicola Asuni. This code is therefor licensed under LGPLv3.

No support for...

We do not support any 2D barcodes, like QR codes. We also only generate the 'bars' part of a barcode. If you want text of the code below the barcode, you could add it later to the output of this package.

Installation

Install through composer:

composer require picqer/php-barcode-generator

If you want to generate PNG or JPG images, you need the GD library or Imagick installed on your system as well.

Usage

Initiate the barcode generator for the output you want, then call the ->getBarcode() routine as many times as you want.

<?php
require 'vendor/autoload.php';

// This will output the barcode as HTML output to display in the browser
$generator = new Picqer\Barcode\BarcodeGeneratorHTML();
echo $generator->getBarcode('081231723897', $generator::TYPE_CODE_128);

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)

Example of usage of all parameters:

<?php

require 'vendor/autoload.php';

$redColor = [255, 0, 0];

$generator = new Picqer\Barcode\BarcodeGeneratorPNG();
file_put_contents('barcode.png', $generator->getBarcode('081231723897', $generator::TYPE_CODE_128, 3, 50, $redColor));

Image types

$generatorSVG = new Picqer\Barcode\BarcodeGeneratorSVG(); // Vector based SVG
$generatorPNG = new Picqer\Barcode\BarcodeGeneratorPNG(); // Pixel based PNG
$generatorJPG = new Picqer\Barcode\BarcodeGeneratorJPG(); // Pixel based JPG
$generatorHTML = new Picqer\Barcode\BarcodeGeneratorHTML(); // Pixel based HTML
$generatorHTML = new Picqer\Barcode\BarcodeGeneratorDynamicHTML(); // Vector based HTML

Accepted barcode types

These barcode types are supported. All types support different character sets or have mandatory lengths. Please see wikipedia for supported chars and lengths per type.

Most used types are TYPE_CODE_128 and TYPE_CODE_39. Because of the best scanner support, variable length and most chars supported.

  • TYPE_CODE_39
  • TYPE_CODE_39_CHECKSUM
  • TYPE_CODE_39E
  • TYPE_CODE_39E_CHECKSUM
  • TYPE_CODE_93
  • TYPE_STANDARD_2_5
  • TYPE_STANDARD_2_5_CHECKSUM
  • TYPE_INTERLEAVED_2_5
  • TYPE_INTERLEAVED_2_5_CHECKSUM
  • TYPE_CODE_128
  • TYPE_CODE_128_A
  • TYPE_CODE_128_B
  • TYPE_CODE_128_C
  • TYPE_EAN_2
  • TYPE_EAN_5
  • TYPE_EAN_8
  • TYPE_EAN_13
  • TYPE_UPC_A
  • TYPE_UPC_E
  • TYPE_MSI
  • TYPE_MSI_CHECKSUM
  • TYPE_POSTNET
  • TYPE_PLANET
  • TYPE_RMS4CC
  • TYPE_KIX
  • TYPE_IMB
  • TYPE_CODABAR
  • TYPE_CODE_11
  • TYPE_PHARMA_CODE
  • TYPE_PHARMA_CODE_TWO_TRACKS

See example images for all supported barcode types

A note about PNG and JPG images

If you want to use PNG or JPG images, you need to install Imagick or the GD library. This package will use Imagick if that is installed, or fall back to GD. If you have both installed but you want a specific method, you can use $generator->useGd() or $generator->useImagick() to force your preference.

Examples

Embedded PNG image in HTML

$generator = new Picqer\Barcode\BarcodeGeneratorPNG();
echo '<img src="data:image/png;base64,' . base64_encode($generator->getBarcode('081231723897', $generator::TYPE_CODE_128)) . '">';

Save JPG barcode to disk

$generator = new Picqer\Barcode\BarcodeGeneratorJPG();
file_put_contents('barcode.jpg', $generator->getBarcode('081231723897', $generator::TYPE_CODABAR));

Oneliner SVG output to disk

file_put_contents('barcode.svg', (new Picqer\Barcode\BarcodeGeneratorSVG())->getBarcode('6825ME601', Picqer\Barcode\BarcodeGeneratorSVG::TYPE_KIX));

GitHub

https://github.com/picqer/php-barcode-generator
Comments
  • 1. Feature/2.0

    Possible 2.0 Release

    • Refactored everything. Barcode data is broken into classes, along with render interfaces for the supported file types (jpg, png, html, svg)
    • Factory generators for Types and Renders.
    • PHP 7 type casting for parameters and return values.
    • Smoke tests for all combinations of code types and renders.
    • phpunit updated to include code coverage report.
    • Updated Readme to demonstrate new way initiating and generating a barcode.

    New Usage

    $generator = new BarcodeGenerator('012345678', BarcodeType::TYPE_CODE_128, BarcodeRender::RENDER_JPG);
    
    // Generates our default barcode with width=2, height=30, color=#000000
    $generated = $generator->generate();
    
    // Generates the same code with style updates
    $generated = $generator->generate(4, 50, '#FFCC33');
    

    Things still needed

    • Unit test coverage is more of a smoke test. No errors occur in calling all types with all renders, but wether that is valid is still unsure.
    • Unit test validating proper exceptions are thrown.
    Reviewed by griffithben at 2019-04-30 04:57
  • 2. Height & Width Issue

    I am using picqer bar code generator for generating bar code. My requirement for bar code height is 26.45 pixels and width is 185.19 pixels. Height is adjustable. But I want width to be precise 185 or 186. How can I do that? I have adjusted height as 27 but How can i set the width of bar code of 186. Your early reply will be appreciated.

    Reviewed by rushiwebonomics at 2016-05-05 08:25
  • 3. PHP 7.4

    This PR contains two commits related to supporting later versions of PHP.

    The main bulk is feae1e0 which fixes all string and array index access using {} which was deprecated in PHP 7.4.

    The second commit fixes a failing test in PHP 7.1 and onward.

    Reviewed by pilif at 2019-09-06 13:11
  • 4. variable barcode type

    Hello there, I'm trying to use variable instead of const, but gives me some errors

    $generator = new Picqer\Barcode\BarcodeGeneratorSVG();
    $generated = $generator->getBarcode('1234567890', $generator:: $barcode_type);
    

    error:

    PHP Fatal error: Uncaught Error: Access to undeclared static property: Picqer\Barcode\BarcodeGeneratorSVG::$barcode_type

    thanks

    Reviewed by Mr-TOA at 2019-12-02 15:30
  • 5. GS1-128

    I need to generate a barcode with the standard GS1-128, I had an almost satisfactory result following this post (http://stackoverflow.com/questions/34040995/how-to-properly-generate-a-gs1-128-formerly Barcode-in-tcpdf) but unfortunately the end of the barcode was not the same in comparison to one generated by other system that actually follows the standard and is accepted by our bank.

    I expect to see this: esperado

    but instead I get this: obtenido

    I'm using this code: $code = chr(241)."4157709998016989802000105385555480202016103470"; $generatorPNG = new Picqer\Barcode\BarcodeGeneratorPNG(); echo '<img ' . 'src="data:image/png;base64,' . base64_encode( $generatorPNG->getBarcode($code, Picqer\Barcode\BarcodeGeneratorPNG::TYPE_CODE_128_C)) . '" style="height: 50px; width: 300px ">';

    I appreciate any help you can give me.

    Reviewed by linaocampouam at 2017-02-17 00:17
  • 6. Text in the bottom of the barcode

    Hello,

    Is there any way I can show the actual code of the generated barcode or a custom text in the bottom part of the generated barcode image?

    I would also like to suggest this as a feature for future versions, which I found useful.

    Thanks in advance.

    Reviewed by robertripoll at 2016-08-02 10:54
  • 7. Mixup A/B/C in 128 barcodes

    Hi,

    I need to use A+C modes in same 128 barcode. I tried to edit current code but it doesnt seems to work. There is a way to adapt it to get this use case works ?

    Thanks

    Reviewed by simondaigre at 2017-03-02 15:31
  • 8. copyright and license violation

    This project is using code copied from: https://github.com/tecnickcom/TCPDF but all copyright and license terms were removed. Please immediately delete all the copied code or adapt it to conform the original copyright and license requirements.

    Please also note that the code you have copied has now been replaced by another project: https://github.com/tecnickcom/tc-lib-barcode

    Please carefully read the license and act promptly.

    Reviewed by nicolaasuni at 2015-08-21 07:53
  • 9. [feature] set background color and padding (or border)

    We are using the library in one of our mobile app and it would be nice if we could set the border around the code. Why? Problem is when on the mobile the dark mode is enabled, because code merges on the left and right side with black background. Is there any workaround with Imagick maybe?

    Reviewed by pubi at 2021-11-10 15:48
  • 10. Black block in place of bacorde

    Hello !

    Thanks for the work on this module. I've updated from 0.x to 2.x and now, i've got a black block in place of my barcode image using : $barcode_generator = new Picqer\Barcode\BarcodeGeneratorJPG(); echo '<img src="data:image/jpg;base64,'.base64_encode($barcode_generator->getBarcode('081231723897',$barcode_generator::TYPE_EAN_13)).'"/>';

    Previously, the same code worked well. What's wrong here, please ?

    Reviewed by jomofcw at 2020-06-29 15:40
  • 11. phar error: invalid path, contains star

    I'm using Satis to host a private package registry, there seems to be an issue with packaging recent version into PHAR archive because of a filename with *:

    Dumping package 'picqer/php-barcode-generator' in version 'dev-master'.
      - Installing picqer/php-barcode-generator (dev-master fd18d04): Cloning fd18d04d64 from cache
    
                                                                                   
      [BadMethodCallException]                                                     
      Entry tests/verified-files/C128-1234567890abcABC-283*33.svg cannot be creat  
      ed: phar error: invalid path "tests/verified-files/C128-1234567890abcABC-28  
      3*33.svg" contains star                                                      
    
    Reviewed by MakG10 at 2020-01-15 10:07
  • 12. Barcode output is different deppends on server

    I have to migrate my application to another server and i saw a difference on barcode:

    Before: barcode-febore

    After: barcode-after

    PHP: $generatorBarcode = new BarcodeGeneratorPNG(); $barcode = $generatorBarcode->getBarcode($produto->getCodigo(), $generatorBarcode::TYPE_CODE_128, 1, 30); $barcodeHtml = '';

    How can i fix this. Now i cant read this barcode...

    Reviewed by JoaoVictorSarzi at 2022-05-13 15:11
  • 13. Invalid XML when using SVG generator for type Code 93

    Hi there!

    I've found another error. When using the SVG generator to export a Code 93 barcode as SVG, the exported XML contains error, if the content of the barcode contains extended characters (there is no problem when using the basic characters).

    The problem has two sources. Removing one of them would remove the problem.

    The first source is the encoding of extended characters in \Picqer\Barcode\Types\TypeCode93::getBarcodeData(). Extended characters are using helping characters defined in the basic character set. These helping characters have been defined in $encoding by using chr() with numbers from 128 to 131. chr() produces (at least in my environment) when concatenating the string "????" (because they are unknown).

    The second source is the desc-tag inside the XML. It uses $barcodeData->getBarcode() as content and - in combination with the first source - fills it with the damaged helping characters. When using the created XML, I get an error that the XML is damaged due to these characters.

    The first source could be fixed by using other characters as helping characters (E.g. 'a', 'b', 'c' and 'd', of which the character codes are below 128 and would work. Because they are not part of the basic character set for Code 93, they could be used as helping characters).

    The second source could be fixed by either removing the desc-tag from XML, or by injecting the encoded string instead of the decoded string of the barcode's content (e.g. 'a' instead of '?A').

    I would suggest to remove both problem sources. The first one, because it could make problems in other situations. The second one using the second approach, because it could make problems with other types of barcodes.

    Kind regards,

    Bernhard

    EDIT 1:

    I just found the same problem using type Code 128. When a control character is used in the barcode's content, it is injected into the XML's desc-tag (causing errors). Control characters should be stripped from string before injecting it into the desc-tag.

    Reviewed by Bernhard-Krop at 2021-08-26 11:08
  • 14. Error with Code 11 using check digit K

    Hi there!

    I have found an error when creating a barcode of type "Code 11", which is at least 10 characters long. In that case, the check digit K is calculated and always (under all circumstances) throws an error.

    The damaged code is in \Picqer\Barcode\Types\TypeCode11::getCheckDigitK() on line 94 (for ($i = strlen($code); $i >= 0; --$i) {), throwing an error on line 95 ($digit = $code[$i];).

    E.g., if the code is 11 characters long (check digit C already included), the code tries to get the 12. character.

    A solution (which is already implemented in ::getCheckDigitC(), for example) would be for ($i = (strlen($code) - 1); $i >= 0; --$i) {.

    Kind regards,

    Bernhard

    Reviewed by Bernhard-Krop at 2021-08-25 13:03
  • 15. Leading zeros for Standard 2 of 5

    Hi there!

    My question is whether the leading zeros are required?

    My barcode scanners (I'm using two) cannot read the barcodes with leading zeros. Reading the article on Wikipedia, I have found nothing that suggests that a barcode must always consist out of an even number of digits. Even the example there has an odd number of digits (the code "123456" is even, but with the checksum digit it is odd).

    I have looked over several pages with barcodes of type Standard 2 of 5 and my barcode scanners could read them all (with or without checksum; with odd or even code length). So that how I've come to my question above. I don't think, the leading zero is required. And regarding my other issue, using leading zeros is also providing errors.

    Kind regards,

    Bernhard

    EDIT 1:

    The same question is regarding the type "Interleaved 2 of 5".

    Reviewed by Bernhard-Krop at 2021-08-18 10:18
  • 16. Error with Standard 2 of 5 with Checksum

    Hi there!

    I think I've found an error with barcodes of type "Standard 2 of 5" with checksum. When having an even content for the barcode (e.g. "5555512372"), then the checksum is generated for this content and padded at the end of the content (making it odd). Then, because it's now an odd length, a zero is padded at the left to making the content length even again.

    And this is exactly the error I've found. The zero is not part of the checksum; which makes it impossible to read the barcode, when set in settings that checksums are required (because the checksum is wrong, due to the missing leading zero while calculating the checksum). Because the checksum is wrong for the barcode, the scanner refuses to show it to me.

    The error is in Picqer\Barcode\Types\TypeStandard2of5::getBarcodeData() in lines 31 to 38. The padding zero must be part of the checksum, therefore the if-statements must be swapped and the condition for the if-statement of the padding zero must be adapted to take the checksum's digit into account.

    Current code with error:

    if ($this->checksum) {
        // add checksum
        $code .= $this->checksum_s25($code);
    }
    if ((strlen($code) % 2) != 0) {
        // add leading zero if code-length is odd
        $code = '0' . $code;
    }
    

    Code suggestion without error:

    $strlen = strlen($code);
    
    if ($this->checksum) {
        // take additional digit of checksum into account
        $strlen++;
    }
    if (($strlen % 2) != 0) {
        // add leading zero if code-length is odd
        $code = '0' . $code;
    }
    if ($this->checksum) {
        // add checksum
        $code .= $this->checksum_s25($code);
    }
    

    I hope the error will soon be fixed.

    Kind regards,

    Bernhard

    EDIT 1:

    I have found several barcodes of that type without leading zeros and odd code length. All of them can be read by my scanners. That's why I have opened another issue.

    If leading zeros are not required and can be removed, this issue's problem would be fixed, too. Therefore, the other issue should be discussed first. At least I think so.

    EDIT 2:

    I could find the same problem in the type "Interleaved 2 of 5" with checksum.

    Reviewed by Bernhard-Krop at 2021-08-18 10:02
Run multiple websites using the same Laravel installation while keeping tenant specific data separated for fully independent multi-domain setups, previously github.com/hyn/multi-tenant

The unobtrusive Laravel package that makes your app multi tenant. Serving multiple websites, each with one or more hostnames from the same codebase. B

May 16, 2022
Run multiple websites using the same Laravel installation while keeping tenant specific data separated for fully independent multi-domain setups.

Tenancy for Laravel Enabling awesome Software as a Service with the Laravel framework. This is the successor of hyn/multi-tenant. Feel free to show su

May 17, 2022
Run multiple websites using the same Laravel installation while keeping tenant specific data separated for fully independent multi-domain setups, previously

Run multiple websites using the same Laravel installation while keeping tenant specific data separated for fully independent multi-domain setups, previously

May 26, 2022
Laravel Design Pattern Generator (api generator)
Laravel Design Pattern Generator (api generator)

Laravel Design Pattern Generator (api generator) you can create your restful api easily by using this library and you can filter, sort and include elo

May 10, 2022
Deploy and execute non-PHP AWS Lambda functions from your Laravel application.

Sidecar for Laravel Deploy and execute non-PHP AWS Lambda functions from your Laravel application. Read the full docs at hammerstone.dev/sidecar/docs.

May 23, 2022
A nice GUI for Laravel Artisan, ready out of the box, configurable and handy for non-CLI experienced developers.

Artisan UI A nice GUI for Laravel Artisan, ready out of the box, configurable and handy for non-CLI experienced developers. Supported commands must be

Dec 3, 2021
A non-blocking stream abstraction for PHP based on Amp.
A non-blocking stream abstraction for PHP based on Amp.

amphp/byte-stream is a stream abstraction to make working with non-blocking I/O simple. Installation This package can be installed as a Composer depen

May 16, 2022
Nebula is a minimalistic and easy to use administration tool for Laravel applications, made with Laravel, Alpine.js, and Tailwind CSS.

Nebula Nebula is a minimalistic and easy to use administration tool for Laravel applications, made with Laravel, Alpine.js, and Tailwind CSS. Nebula m

Apr 14, 2022
Laravel Setting - Easily save, update and get titles, descriptions, and more. it is very easy to use.

Laravel Setting Easily save, update and get titles, descriptions, and more. it is very easy to use. This is great for storing and receiving general si

May 9, 2022
Laravel-FCM is an easy to use package working with both Laravel and Lumen for sending push notification with Firebase Cloud Messaging (FCM).

Laravel-FCM Introduction Laravel-FCM is an easy to use package working with both Laravel and Lumen for sending push notification with Firebase Cloud M

Dec 29, 2021
🔹 Generator Template for 🙃 Phony Framework
🔹 Generator Template for 🙃 Phony Framework

?? Generator Template This repository contains the Generator Template for ?? Phony Framework. ?? Start generating fake data with ?? Phony Framework, v

Jan 30, 2022
🧩 Generator Manager for 🙃 Phony Framework
🧩  Generator Manager for 🙃 Phony Framework

?? Generator Manager This repository contains the Generator Manager for ?? Phony Framework. ?? Start generating fake data with ?? Phony Framework, vis

Jan 7, 2022
A premade, easy to use local development setup to be used for authoring Laravel applications

Laravel Drydock This project is a premade, easy to use local development setup to be used for authoring Laravel applications. The deliverables of this

Feb 21, 2020
An easy-to-use virtual wallet implementation for Laravel

Laravel Wallet Some apps require a prepayment system like a virtual wallet where customers can recharge credits which they can then use to pay in app

Apr 25, 2022
Livewire DataTables components for back-end. Modular, easy to use, with tons of features.

Livewire DataTables Livewire DataTables components for back-end. Modular, easy to use, with tons of features. Inspired by Caleb's Livewire Screencasts

May 1, 2022
Laravel User Activity Log - a package for Laravel 8.x that provides easy to use features to log the activities of the users of your Laravel app
Laravel User Activity Log - a package for Laravel 8.x that provides easy to use features to log the activities of the users of your Laravel app

Laravel User Activity Log - a package for Laravel 8.x that provides easy to use features to log the activities of the users of your Laravel app

Apr 20, 2022
An easy-to-use virtual wallet implementation for Laravel.

Laravel Wallet Some apps require a prepayment system like a virtual wallet where customers can recharge credits which they can then use to pay in app

Feb 6, 2022
A super simple package allowing for use MySQL 'USE INDEX' and 'FORCE INDEX' statements.
A super simple package allowing for use MySQL 'USE INDEX' and 'FORCE INDEX' statements.

Laravel MySQL Use Index Scope A super simple package allowing for use MySQL USE INDEX and FORCE INDEX statements. Requirements PHP ^7.4 | ^8.0 Laravel

Feb 21, 2022
A simple to use query builder for the jQuery QueryBuilder plugin for use with Laravel.
A simple to use query builder for the jQuery QueryBuilder plugin for use with Laravel.

QueryBuilderParser Status Label Status Value Build Insights Code Climate Test Coverage QueryBuilderParser is designed mainly to be used inside Laravel

Jan 25, 2022