Skip to content

Standalone SVG Barcode Export

Dragon edited this page Jun 3, 2026 · 1 revision

Standalone SVG Barcode Export

SvgBarcodeRenderer exports QR Code, DataMatrix, and Aztec Code barcodes as self-contained SVG strings - no PDF document is involved. This is useful when the same application needs to display a barcode on screen (or in an <img> tag) and also embed it in a PDF, without depending on a second barcode library.

Basic usage

use DragonOfMercy\PhpPdf\Barcode\QrCode;
use DragonOfMercy\PhpPdf\Barcode\Svg\SvgBarcodeRenderer;

// Render as an SVG string.
$svg = (new SvgBarcodeRenderer())->render(QrCode::of('https://example.com'), 200, 200);
// Returns: "<svg xmlns='...' width='200' height='200' viewBox='0 0 N N'>...</svg>"

// Base64 data URI for inline <img src="..."> usage.
$uri = SvgBarcodeRenderer::renderDataUri(QrCode::of('https://example.com'), 200, 200);

// Without the white background rectangle (e.g. over a non-white canvas).
$svg = (new SvgBarcodeRenderer())->withoutBackground()->render($code, 200, 200);

API reference

Constructor

new SvgBarcodeRenderer(bool $background = true)

Creates a renderer. When $background is true (the default), a white <rect> is emitted behind the modules to guarantee contrast on any background.

Instance methods

Method Returns Description
->render(Barcode $barcode, int $width, int $height): string string Encodes the barcode and returns a complete SVG document. $width and $height are the pixel dimensions of the <svg> element.
->withoutBackground(): self SvgBarcodeRenderer Returns a new instance that omits the background rectangle.

Static methods

Method Returns Description
SvgBarcodeRenderer::renderDataUri(Barcode $barcode, int $width, int $height): string string Convenience wrapper: renders and returns data:image/svg+xml;base64,.... Always includes the white background.

Supported and unsupported formats

Format Supported
QR Code Yes
DataMatrix Yes
Aztec Code Yes
Code 128, EAN-13, EAN-8, UPC-A, Code 39, Code 93, ITF No - throws PdfException
PDF417 No - throws PdfException

1D codes and PDF417 are not supported because their human-text layouts and bearer bars require PDF text metrics. Use Page::barcode() to render them into a PDF.

Foreground color and viewBox

Foreground color is taken from the barcode value object: call ->withColor(Color $c) on the barcode before passing it to the renderer.

use DragonOfMercy\PhpPdf\Color;
use DragonOfMercy\PhpPdf\Barcode\DataMatrix;
use DragonOfMercy\PhpPdf\Barcode\Svg\SvgBarcodeRenderer;

$code = DataMatrix::of('INV-2026-001')->withColor(Color::hex('#1a3c6e'));
$svg  = (new SvgBarcodeRenderer())->render($code, 150, 150);

The SVG uses viewBox in module units (quiet zone included), with the requested width and height attributes as pixel dimensions. The matrix scales responsively while remaining square.

See also

Clone this wiki locally