Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Tc Lib Barcode Laravel Package

tecnickcom/tc-lib-barcode

Pure-PHP barcode generator for linear and 2D symbologies. Spec-driven, deterministic encoding suitable for labels, tickets, logistics, and compliance docs. Generate barcode data once and render as vector or raster output.

View on GitHub
Deep Wiki
Context7

Getting Started

Install the package via Composer:

composer require tecnickcom/tc-lib-barcode

First Use Case: Generate a QR code for a URL in a Laravel controller:

use Com\Tecnick\Barcode\Barcode;

public function generateQrCode()
{
    $barcode = new Barcode();
    $bobj = $barcode->getBarcodeObj(
        type: 'QRCODE,H',
        code: 'https://example.com',
        width: 3,
        height: 3,
        color: 'black',
        padding: [2, 2, 2, 2]
    )->setBackgroundColor('white');

    return response($bobj->getPngImage(), 200, ['Content-Type' => 'image/png']);
}

Where to Look First:

  • Example Directory for ready-to-use snippets.
  • API Docs for format-specific parameters.
  • Barcode.php class for core methods like getBarcodeObj(), getHtmlDiv(), and getPngImage().

Implementation Patterns

Core Workflow

  1. Instantiate the Barcode Class:
    $barcode = new \Com\Tecnick\Barcode\Barcode();
    
  2. Generate Barcode Object:
    $bobj = $barcode->getBarcodeObj(
        type: 'EAN13',       // Format (see supported list)
        code: '1234567890128', // Data to encode
        width: 1,            // Relative width (1 = default)
        height: 1,           // Relative height (1 = default)
        color: 'black',      // Foreground color
        padding: [1, 1, 1, 1] // [top, right, bottom, left] padding
    );
    
  3. Customize Appearance:
    $bobj->setBackgroundColor('white')
         ->setDisplayText(true) // Show human-readable text
         ->setFontSize(10);     // Adjust text size
    
  4. Render Output:
    // For web responses
    return response($bobj->getPngImage(), 200, ['Content-Type' => 'image/png']);
    
    // For Blade templates
    echo $bobj->getHtmlDiv();
    
    // For PDFs (via TCPDF or DomPDF)
    $svg = $bobj->getSvgImage();
    

Laravel-Specific Patterns

Service Provider Integration

Register the barcode generator as a singleton in AppServiceProvider:

public function register()
{
    $this->app->singleton(\Com\Tecnick\Barcode\Barcode::class);
}

Facade for Clean Syntax

Create a facade (php artisan make:facade Barcode) and bind it:

// app/Facades/Barcode.php
public static function ean13($code)
{
    return app(\Com\Tecnick\Barcode\Barcode::class)
        ->getBarcodeObj('EAN13', $code)
        ->setDisplayText(true);
}

Usage in Blade:

{{ Barcode::ean13('1234567890128')->getHtmlDiv() }}

Queueable Barcode Generation

For batch processing:

// app/Jobs/GenerateBarcodeJob.php
public function handle()
{
    $barcode = Barcode::ean13($this->code);
    Storage::put("barcodes/{$this->id}.png", $barcode->getPngImage());
}

Dynamic Routes for Barcodes

// routes/web.php
Route::get('/barcode/{type}/{code}', function ($type, $code) {
    $barcode = app(\Com\Tecnick\Barcode\Barcode::class)
        ->getBarcodeObj($type, $code)
        ->getPngImage();
    return response($barcode, 200, ['Content-Type' => 'image/png']);
});

Usage:

<img src="/barcode/QRCODE,https://example.com" alt="QR Code">

Blade Components

Create a reusable component (app/View/Components/Barcode.php):

public function render()
{
    $barcode = app(\Com\Tecnick\Barcode\Barcode::class)
        ->getBarcodeObj($this->type, $this->code)
        ->getHtmlDiv();
    return <<<HTML
    <div class="barcode-container">
        {$barcode}
    </div>
    HTML;
}

Usage in Blade:

<x-barcode type="EAN13" code="1234567890128" />

PDF Integration (TCPDF/DomPDF)

use TCPDF;

// Generate barcode as SVG
$svg = Barcode::ean13('1234567890128')->getSvgImage();

// Add to PDF
$pdf = new TCPDF();
$pdf->AddPage();
$pdf->writeHTML($svg, true, false, true, false, '');
$pdf->Output('invoice.pdf', 'D');

Gotchas and Tips

Pitfalls

  1. PHP Extensions Missing:

    • Error: Class 'GdImage' not found or bcmath warnings.
    • Fix: Ensure gd, bcmath, and pcre extensions are enabled. For Docker:
      RUN docker-php-ext-install gd bcmath pcre
      
  2. Memory Limits for Large Barcodes:

    • Error: Allowed memory size exhausted when generating complex 2D barcodes (e.g., PDF417).
    • Fix: Increase memory_limit in php.ini or optimize dimensions:
      $bobj->setScale(0.5); // Reduce size
      
  3. Invalid Barcode Data:

    • Error: Silent failure or malformed output for invalid data (e.g., non-numeric EAN codes).
    • Fix: Validate input before generation:
      if (!preg_match('/^\d{13}$/', $eanCode)) {
          throw new \InvalidArgumentException('Invalid EAN-13 code');
      }
      
  4. SVG Output Issues:

    • Error: SVG may render incorrectly in some browsers or PDF converters.
    • Fix: Use PNG for critical applications or test SVG output in target environments.
  5. Case Sensitivity in Formats:

    • Error: getBarcodeObj('ean13') may fail if the format is case-sensitive.
    • Fix: Use uppercase format names (e.g., 'EAN13', 'QRCODE,H').
  6. Postal Barcode Quirks:

    • Error: POSTNET/IMB formats require specific data lengths (e.g., 5 digits for POSTNET).
    • Fix: Pad or validate input:
      $postnetCode = str_pad($zipCode, 5, '0', STR_PAD_LEFT);
      

Debugging Tips

  • Inspect Raw Output:
    $rawData = $bobj->getUnicode(); // Debug barcode content
    
  • Log Configuration:
    \Com\Tecnick\Barcode\Barcode::setDebug(true); // Enable debug mode
    
  • Test with Minimal Examples: Start with simple formats (e.g., CODE128) before complex ones like PDF417.

Configuration Quirks

  1. Default Dimensions:
    • Negative values (e.g., width: -4) scale relative to the default. Use 1 for default size.
  2. Color Formats:
    • Accepts hex ('#000000'), named ('black'), or RGB ('rgb(0,0,0)') colors.
  3. Display Text:
    • setDisplayText(true) adds human-readable text below the barcode. Disable for space-sensitive labels.
  4. Padding:
    • Padding is applied as [top, right, bottom, left]. Use 0 for no padding.

Extension Points

  1. Custom Formats:
    • Extend the library by subclassing \Com\Tecnick\Barcode\Barcode and overriding getBarcodeObj().
  2. Output Filters:
    • Post-process SVG/PNG output (e.g., add logos) before rendering:
      $svg = $bobj->getSvgImage();
      $svg = str_replace('<svg', '<svg xmlns:xlink="http://www.w3.org/1999/xlink"', $svg);
      
  3. Caching:
    • Cache generated barcodes (e.g., in Redis or filesystem) to avoid reprocessing:
      $cacheKey = "barcode:{$type}:{$code}";
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky