跳轉到

條碼指南

先決條件

# 一維 + 二維條碼(Core,免費)
composer require nextpdf/core

# 特殊條碼(GS1、郵政、醫療)
composer require nextpdf/pro

Core:支援的條碼格式

一維條碼

格式 用途 最大長度
Code 128 通用物流 無限制
Code 39 工業、汽車業 無限制
EAN-13 零售商品 12 位數字
EAN-8 小型商品 7 位數字
UPC-A 北美零售 11 位數字
UPC-E 小型商品 6 位數字
ITF-14 物流箱碼 14 位數字
Codabar 血庫、快遞 可變長度
Code 93 高密度英數字 可變長度

二維條碼

格式 用途 最大容量
QR Code 通用、URL 7,089 字元
Data Matrix 小型零件標記 3,116 字元
PDF417 文件、駕照 1,850 文字字元
Aztec 票務、身分 3,832 位元組
MaxiCode UPS 物流 93 字元
MicroQR 極小空間 35 字元

基本用法

use NextPDF\Core\Barcode\BarcodeRenderer;
use NextPDF\Core\Barcode\Encoders\QrCodeEncoder;
use NextPDF\Core\Barcode\ValueObjects\BarcodeOptions;
use NextPDF\Core\ValueObjects\Position;
use NextPDF\Core\ValueObjects\Dimension;

$barcode = $document->barcodes();

// QR Code
$barcode->render(
    encoder:  QrCodeEncoder::create(
        data:         'https://nextpdf.dev',
        errorLevel:   'M',
        quietZone:    4,
    ),
    position:  Position::at(x: 25.0, y: 50.0),
    dimension: Dimension::square(size: 40.0),
);

EAN-13 零售條碼

use NextPDF\Core\Barcode\Encoders\Ean13Encoder;

$barcode->render(
    encoder:   Ean13Encoder::create(data: '978020137962'),  // ISBN
    position:  Position::at(x: 25.0, y: 150.0),
    dimension: Dimension::create(width: 50.0, height: 30.0),
    options:   BarcodeOptions::create()->withHumanReadable(true),
);

Code 128 物流條碼

use NextPDF\Core\Barcode\Encoders\Code128Encoder;

$barcode->render(
    encoder:   Code128Encoder::create(data: 'SHIPMENT-2024-001'),
    position:  Position::at(x: 25.0, y: 200.0),
    dimension: Dimension::create(width: 80.0, height: 20.0),
    options:   BarcodeOptions::create()
        ->withHumanReadable(true)
        ->withFontSize(8.0)
        ->withColor('#000000'),
);

PDF417 文件條碼

use NextPDF\Core\Barcode\Encoders\Pdf417Encoder;

$barcode->render(
    encoder:   Pdf417Encoder::create(
        data:            'ID:A123456789;Name:Wang,Xiaoming;DOB:19900101',
        rows:            10,
        columns:         5,
        errorCorrection: 2,
    ),
    position:  Position::at(x: 25.0, y: 250.0),
    dimension: Dimension::create(width: 80.0, height: 25.0),
);

Pro:特殊條碼格式

use NextPDF\Pro\Barcode\Encoders\Gs1128Encoder;
use NextPDF\Pro\Barcode\Encoders\GS1DataBarEncoder;

// GS1-128 供應鏈條碼
$barcode->render(
    encoder:   Gs1128Encoder::create(
        applicationIdentifiers: [
            '01' => '09521234543213',   // GTIN
            '17' => '261231',           // 有效期限
            '10' => 'ABC123',           // 批次號
        ],
    ),
    position:  Position::at(x: 25.0, y: 300.0),
    dimension: Dimension::create(width: 100.0, height: 20.0),
);

樣式與客製化

$options = BarcodeOptions::create()
    ->withForeground('#000000')
    ->withBackground('#FFFFFF')
    ->withHumanReadable(true)
    ->withFontName('NotoSans')
    ->withFontSize(8.0)
    ->withTextAlignment('center')
    ->withQuietZone(top: 2, right: 2, bottom: 2, left: 2);

批次條碼生成

延伸閱讀