Installation
composer require bitgrave/barcode-bundle
Add the bundle to config/bundles.php:
Paterik\BGBarcodeBundle\PaterikBGBarcodeBundle::class => ['all' => true],
Basic Usage Generate a barcode in a controller:
use Paterik\BGBarcodeBundle\Service\BarcodeService;
class BarcodeController extends AbstractController
{
public function generate(BarcodeService $barcodeService)
{
$barcode = $barcodeService->getBarcode('EAN13', '123456789012');
return new Response($barcode->render());
}
}
First Use Case Render a barcode as an image in a Symfony template:
<img src="{{ path('barcode_generate', {'type': 'EAN13', 'data': '123456789012'}) }}" alt="Barcode">
Define the route in config/routes.yaml:
barcode_generate:
path: /barcode/{type}/{data}
controller: Paterik\BGBarcodeBundle\Controller\BarcodeController::generate
Dynamic Barcode Generation
Use the BarcodeService to generate barcodes dynamically based on user input:
$barcode = $barcodeService->getBarcode($type, $data, [
'width' => 300,
'height' => 100,
'format' => 'png', // or 'svg', 'html'
]);
Batch Processing Generate multiple barcodes in a loop (e.g., for invoices or product labels):
foreach ($products as $product) {
$barcode = $barcodeService->getBarcode('EAN13', $product->getEan());
$this->saveBarcodeImage($barcode->render(), $product->id);
}
QR Code with Custom Error Correction Leverage QR code levels (L, M, Q, H) for varying data capacity:
$qrCode = $barcodeService->getBarcode('QRCODE,M', 'https://example.com');
SVG for Scalability Use SVG format for resolution-independent barcodes (e.g., in PDFs or responsive designs):
$svgBarcode = $barcodeService->getBarcode('EAN13', '123456789012', ['format' => 'svg']);
Twig Integration Extend Twig with a custom filter for inline barcode generation:
// src/Twig/AppExtension.php
public function getFilters()
{
return [
new \Twig\TwigFilter('barcode', [$this, 'generateBarcodeFilter']),
];
}
public function generateBarcodeFilter(BarcodeService $barcodeService, string $type, string $data, array $options = [])
{
return $barcodeService->getBarcode($type, $data, $options)->render();
}
Usage in Twig:
<img src="data:image/png;base64,{{ barcode('EAN13', '123456789012')|base64_encode }}" alt="Barcode">
API Responses Return barcodes as binary responses in APIs:
return new BinaryFileResponse(
$barcodeService->getBarcode('EAN13', $request->get('data'))->render(),
200,
['Content-Type' => 'image/png']
);
Configuration
Override default settings in config/packages/paterik_bg_barcode.yaml:
paterik_bg_barcode:
default_format: svg
default_width: 400
default_height: 150
image_driver: gd # or 'imagick'
Image Driver Dependencies
php-gd or php-imagick).
php -m | grep -E 'gd|imagick' to check availability.paterik_bg_barcode:
image_driver: gd
Memory Limits
memory_limit.memory_limit in php.ini or generate barcodes in chunks:
ini_set('memory_limit', '256M');
Character Encoding
CODE39).$barcodeService->getBarcode('EAN13', mb_convert_encoding($ean, 'ASCII'));
Caching Static Barcodes
$cacheKey = 'barcode_' . md5($type . $data);
$barcode = $cache->get($cacheKey, function() use ($barcodeService, $type, $data) {
return $barcodeService->getBarcode($type, $data);
});
HTML Table Format Quirks
html format renders barcodes as tables, which may not scale well.Validate Barcode Data
Use the validate() method to check if data is compatible with the barcode type:
if (!$barcodeService->getBarcode('EAN13', 'invalid_data')->validate()) {
throw new \InvalidArgumentException('Invalid EAN13 data');
}
Log Errors Enable debug mode to catch barcode generation issues:
# config/packages/dev/paterik_bg_barcode.yaml
paterik_bg_barcode:
debug: true
Check Supported Types
Ensure the barcode type exists (e.g., QRCODE,H for high error correction):
$supportedTypes = $barcodeService->getSupportedTypes(); // Array of valid types
Custom Barcode Types Extend the bundle by adding new barcode types via a custom service:
// src/Service/CustomBarcodeService.php
class CustomBarcodeService extends AbstractBarcodeService
{
public function getBarcode(string $type, string $data, array $options = [])
{
if ($type === 'CUSTOM') {
return $this->generateCustomBarcode($data, $options);
}
return parent::getBarcode($type, $data, $options);
}
}
Override the bundle’s service in config/services.yaml:
Paterik\BGBarcodeBundle\Service\BarcodeService: '@custom_barcode_service'
Post-Processing
Hook into the render() method to modify output (e.g., add a logo):
$barcode->render(function ($image) {
$logo = imagecreatefrompng('logo.png');
imagecopy($image, $logo, 10, 10, 0, 0, imagesx($logo), imagesy($logo));
return $image;
});
Event Listeners Trigger events before/after barcode generation (e.g., log generation):
// src/EventListener/BarcodeListener.php
class BarcodeListener implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return [
Paterik\BGBarcodeBundle\Event\BarcodeEvents::PRE_RENDER => 'onPreRender',
];
}
public function onPreRender(BarcodeEvent $event)
{
$this->logger->info('Generating barcode', [
'type' => $event->getType(),
'data' => $event->getData(),
]);
}
}
Reuse Instances
Inject BarcodeService as a singleton to avoid recreating the service:
// src/Controller/BarcodeController.php
public function __construct(private BarcodeService $barcodeService) {}
Lazy Loading Defer barcode generation until the response phase (e
How can I help you explore Laravel packages today?