# QR Code
Endroid QR Code is a PHP library for generating QR codes in multiple output formats including PNG, WebP, SVG, EPS, PDF, and binary. The library leverages bacon/bacon-qr-code for matrix generation and provides an intuitive fluent Builder API along with direct object instantiation. It supports extensive customization including foreground and background colors, custom logos, text labels, encoding options, error correction levels, and round block size modes for optimal readability.
The library requires PHP 8.4+ and the GD extension for image generation. For QR code validation, it integrates with khanamiryan/qrcode-detector-decoder to verify that generated codes are readable and contain the expected data. A Symfony bundle is available separately for framework integration with additional features like Twig extensions and URL-based QR code generation.
## Installation
Install the library using Composer.
```bash
composer require endroid/qr-code
```
## Builder Class
The Builder class provides a fluent, all-in-one interface for generating QR codes with full customization including QR code data, colors, logos, labels, and output format selection.
```php
build();
// Save to file
$result->saveToFile('/path/to/qrcode.png');
// Or override options at build time
$result = $builder->build(
data: 'https://different-url.com',
size: 400,
labelText: 'Different Label'
);
```
## QrCode Class
The QrCode class represents a QR code configuration with data, encoding, size, margins, colors, and error correction settings. Use it for direct control when combining with writers manually.
```php
getData(); // 'Life is too short...'
echo $qrCode->getSize(); // 300
echo $qrCode->getMargin(); // 10
echo $qrCode->getErrorCorrectionLevel()->value; // 'low'
```
## Logo Class
The Logo class allows embedding an image (logo) in the center of the QR code with optional resizing and background punchout for better visibility.
```php
getPath(); // '/path/to/company-logo.png'
echo $logo->getResizeToWidth(); // 50
echo $logo->getPunchoutBackground(); // true
```
## Label Class
The Label class adds customizable text below the QR code with font, alignment, margin, and color options.
```php
getRed(); // 0
echo $black->getGreen(); // 0
echo $black->getBlue(); // 0
echo $black->getAlpha(); // 0
echo $black->getOpacity(); // 1.0
echo $black->getHex(); // '#000000'
// Convert to array
$colorArray = $black->toArray();
// ['red' => 0, 'green' => 0, 'blue' => 0, 'alpha' => 0]
```
## PngWriter
The PngWriter generates QR codes as PNG images with support for logos, labels, compression settings, and validation.
```php
write($qrCode, $logo, $label, [
PngWriter::WRITER_OPTION_COMPRESSION_LEVEL => 9, // 0-9
PngWriter::WRITER_OPTION_NUMBER_OF_COLORS => 16 // 1-256 or null for true color
]);
// Validate the generated QR code is readable
$writer->validateResult($result, 'https://example.com');
// Output the image
header('Content-Type: ' . $result->getMimeType());
echo $result->getString();
```
## SvgWriter
The SvgWriter generates QR codes as scalable SVG images with options for XML declaration, width/height attributes, and compact path rendering.
```php
write($qrCode, null, null, [
SvgWriter::WRITER_OPTION_COMPACT => true, // Use path element (smaller file)
SvgWriter::WRITER_OPTION_BLOCK_ID => 'qr-block', // Custom block ID
SvgWriter::WRITER_OPTION_EXCLUDE_XML_DECLARATION => true, // Omit header
SvgWriter::WRITER_OPTION_EXCLUDE_SVG_WIDTH_AND_HEIGHT => true, // For responsive SVGs
SvgWriter::WRITER_OPTION_FORCE_XLINK_HREF => false // Use xlink:href for compatibility
]);
// Get SVG string for embedding in HTML
$svgString = $result->getString();
// Or use the Builder
$builder = new Builder(
writer: new SvgWriter(),
writerOptions: [
SvgWriter::WRITER_OPTION_EXCLUDE_XML_DECLARATION => true
],
data: 'https://example.com',
size: 300
);
$result = $builder->build();
$result->saveToFile('/path/to/qrcode.svg');
```
## WebPWriter
The WebPWriter generates QR codes as WebP images with configurable quality settings, ideal for web use with smaller file sizes.
```php
write($qrCode, null, null, [
WebPWriter::WRITER_OPTION_QUALITY => 80 // 0-100, higher = better quality
]);
// Validate the result
$writer->validateResult($result, 'https://example.com');
// Save to file
$result->saveToFile('/path/to/qrcode.webp');
// Get data URI for inline embedding
$dataUri = $result->getDataUri();
echo "
";
```
## PdfWriter
The PdfWriter generates QR codes directly into PDF documents using FPDF, with support for positioning, custom units, and clickable links.
```php
write($qrCode, $logo, $label, [
PdfWriter::WRITER_OPTION_UNIT => 'mm', // mm, pt, cm, in
PdfWriter::WRITER_OPTION_X => 0, // X offset
PdfWriter::WRITER_OPTION_Y => 0, // Y offset
PdfWriter::WRITER_OPTION_LINK => 'https://example.com' // Clickable link
]);
$result->saveToFile('/path/to/qrcode.pdf');
// Or embed in existing FPDF document
$fpdf = new \FPDF('P', 'mm', 'A4');
$fpdf->AddPage();
$fpdf->SetFont('Helvetica', '', 12);
$fpdf->Cell(0, 10, 'My Document with QR Code');
$result = $writer->write($qrCode, null, null, [
PdfWriter::WRITER_OPTION_PDF => $fpdf,
PdfWriter::WRITER_OPTION_X => 80,
PdfWriter::WRITER_OPTION_Y => 100
]);
```
## EpsWriter
The EpsWriter generates QR codes as Encapsulated PostScript files, suitable for professional printing and vector graphics applications.
```php
write($qrCode);
// Save to file
$result->saveToFile('/path/to/qrcode.eps');
// Get EPS string
$epsContent = $result->getString();
```
## BinaryWriter
The BinaryWriter outputs the raw QR code matrix as binary data (0s and 1s), useful for custom rendering or data processing.
```php
write($qrCode);
// Get the matrix for custom processing
$matrix = $result->getMatrix();
echo "Block count: " . $matrix->getBlockCount() . "\n";
echo "Block size: " . $matrix->getBlockSize() . "\n";
echo "Outer size: " . $matrix->getOuterSize() . "\n";
echo "Inner size: " . $matrix->getInnerSize() . "\n";
// Iterate through the matrix
for ($row = 0; $row < $matrix->getBlockCount(); $row++) {
for ($col = 0; $col < $matrix->getBlockCount(); $col++) {
echo $matrix->getBlockValue($row, $col) ? '##' : ' ';
}
echo "\n";
}
```
## ResultInterface Methods
All writers return a Result object implementing ResultInterface, providing methods to output, save, and retrieve QR code data.
```php
build();
// Get the raw image/data as string
$rawData = $result->getString();
// Get MIME type for HTTP headers
$mimeType = $result->getMimeType(); // 'image/png', 'image/svg+xml', etc.
// Get data URI for inline HTML embedding
$dataUri = $result->getDataUri();
echo "
";
// Save directly to file
$result->saveToFile('/path/to/output.png');
// Access the underlying matrix
$matrix = $result->getMatrix();
echo "Size: " . $matrix->getOuterSize() . "px\n";
// Output directly to browser
header('Content-Type: ' . $result->getMimeType());
echo $result->getString();
```
## ErrorCorrectionLevel Enum
The ErrorCorrectionLevel enum defines how much of the QR code can be damaged while remaining readable. Higher levels allow for larger logos but result in denser codes.
```php
value; // 'low'
echo ErrorCorrectionLevel::Medium->value; // 'medium'
echo ErrorCorrectionLevel::Quartile->value; // 'quartile'
echo ErrorCorrectionLevel::High->value; // 'high'
```
## RoundBlockSizeMode Enum
The RoundBlockSizeMode enum controls how block sizes are rounded for sharper images and better readability.
```php
9
],
validateResult: true,
data: 'https://example.com/landing-page?utm_source=qr',
encoding: new Encoding('UTF-8'),
errorCorrectionLevel: ErrorCorrectionLevel::High,
size: 400,
margin: 15,
roundBlockSizeMode: RoundBlockSizeMode::Margin,
foregroundColor: new Color(33, 33, 33),
backgroundColor: new Color(255, 255, 255),
logoPath: '/path/to/company-logo.png',
logoResizeToWidth: 80,
logoPunchoutBackground: true,
labelText: 'Scan for Special Offer!',
labelFont: new OpenSans(18),
labelAlignment: LabelAlignment::Center
);
$result = $builder->build();
$result->saveToFile('/var/www/html/promo-qr.png');
// Method 2: Manual object composition
$writer = new PngWriter();
$qrCode = new QrCode(
data: 'https://example.com',
encoding: new Encoding('UTF-8'),
errorCorrectionLevel: ErrorCorrectionLevel::High,
size: 400,
margin: 15,
roundBlockSizeMode: RoundBlockSizeMode::Margin,
foregroundColor: new Color(33, 33, 33),
backgroundColor: new Color(255, 255, 255)
);
$logo = new Logo(
path: '/path/to/logo.png',
resizeToWidth: 80,
punchoutBackground: true
);
$label = new Label(
text: 'Scan Me',
font: new OpenSans(18),
alignment: LabelAlignment::Center,
margin: new Margin(0, 10, 10, 10),
textColor: new Color(100, 100, 100)
);
$result = $writer->write($qrCode, $logo, $label);
// Validate to ensure QR code is readable
$writer->validateResult($result, 'https://example.com');
// Output for web
header('Content-Type: ' . $result->getMimeType());
header('Content-Disposition: inline; filename="qrcode.png"');
echo $result->getString();
```
## Summary
Endroid QR Code is ideal for generating QR codes in PHP applications requiring various output formats. Common use cases include marketing campaigns with branded QR codes (logos and custom colors), product packaging with scannable links, event tickets with validation requirements, business cards with contact URLs, and document generation with embedded PDF QR codes. The library excels in scenarios requiring both visual customization and data integrity validation.
Integration patterns typically involve using the Builder class for straightforward generation or composing QrCode, Logo, Label, and Writer objects manually for maximum flexibility. For Symfony applications, the companion qr-code-bundle provides dependency injection, Twig functions, and route-based generation. The library's writer system allows easy extension for custom output formats, while the validation feature ensures generated codes are scanner-readable before deployment.