barcode

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 5, 2026 License: MIT Imports: 28 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

laravel-go-barcode

CI Go reference docs Go 1.27.0

Go port of milon/barcode: generate 1D and 2D barcodes as SVG, HTML and PNG, and 1D barcodes as JPEG, for Go and Laravel for Go.

It covers all 31 linear symbologies of the PHP package (Code 39, Code 93, Code 128, GS1-128, EAN and UPC, 2 of 5, MSI, postal codes, Codabar, Code 11 and Pharmacode) and QR Code, Data Matrix and PDF417, including Macro PDF417. The root package barcode has no web framework dependency; the laravelbarcode subpackage adds Laravel for Go services, template functions, responses and file storage. Output is checked against fixtures recorded by running the PHP package.

Status: pre-release. The first release is v0.1.0.

Quick start

go get github.com/bowerbird-si/laravel-go-barcode
package barcode_test

import (
	"fmt"
	"strings"

	"github.com/bowerbird-si/laravel-go-barcode"
)

func Example() {
	generator, err := barcode.New1D(barcode.InlineSVG(true), barcode.Padding(10))
	if err != nil {
		panic(err)
	}
	svg, err := generator.SVG("SKU-1042", barcode.C128)
	if err != nil {
		panic(err)
	}
	qr, err := barcode.QR(barcode.QRErrorCorrection(barcode.QRHigh))
	if err != nil {
		panic(err)
	}
	uri, err := (barcode.Generator2D{}).DataURI("https://example.test/item/7", qr, barcode.PNGFormat)
	if err != nil {
		panic(err)
	}
	fmt.Println(strings.HasPrefix(string(svg), "<svg "))
	fmt.Println(strings.HasPrefix(uri, "data:image/png;base64,"))
	// Output:
	// true
	// true
}

CI runs this example from example_test.go.

The guide covers every format, the options, Laravel for Go and file storage.

PHP parity

Follows milon/barcode v13.6.0 (commit aff97c2d830c).

Parity level Abilities Covered Diverged Planned PHP fixtures Last verified
full 75 62 13 0 205 2026-12-05

Every ability is listed in parity.toml, with the tests that cover it or the reason it differs.

Differences from PHP

Most differences follow one rule: the port does not change the caller's data without saying so (decision 0001).

Encoding

  • Codabar keeps the start and stop letters (A to D) the caller supplies and adds A only at an end without one; a letter A to D inside the data is an error. PHP always adds A at both ends, so A1234B becomes AA1234BA.
  • Code 39 Full ASCII (C39E, C39E+) and Code 93 (C93) keep lowercase letters. PHP uppercases the input first, so a and A produce the same bars.
  • Vertical tab. The same three types encode byte 0x0B as the standards define it. PHP rejects it.
  • Code 128 control runs. In automatic C128, a run of two or more bytes that needs the other subset gets a Code A or Code B latch; a Shift is used for one byte only. PHP can put one Shift before a run of control bytes, so a scanner reads back different bytes: for 41 42 03 04 04 42 PHP's symbol decodes as 41 42 03 64 64 42, the port's as the input. For this case the test decodes the port's symbol instead of comparing bars with PHP's.
  • Empty 2 of 5. S25, S25+, I25 and I25+ need at least one digit (ErrInvalidCode). PHP draws a symbol from empty input.
  • QR backslash and zero. The two-byte payload \0 (0x5C 0x30) is encoded and decodes back. PHP rejects it.

Options and output

  • Negative padding is ErrInvalidOption. PHP clamps it to 0.
  • Escaping. Label text is escaped and CSS colours are validated before they go into SVG or HTML. PHP writes both unescaped.
  • Text that does not fit is ErrInvalidOption. With the default height of 30, an EAN8, EAN13, UPCA or UPCE SVG with its digits needs Height(31) or more. PHP draws the digits over the bars, or negative bar heights for other types. For IMB, RMS4CC and KIX, a visible label needs at least 39 pixels in SVG, 42 in PNG or JPEG, and 75 in HTML at the default font size.
  • Limits. Input length, canvas size, module and font size, logo size and type strings have fixed limits (MaxSide, MaxPixels, MaxModule, MaxLinearInputBytes, MaxInputBytes, MaxLogoBytes and others); exceeding one is an error before anything is allocated. PHP has no limits.

Laravel for Go and stored files

  • Configuration is programmatic: laravelbarcode.New with StoreDir and StoreURL. PHP publishes a config file with barcode.store_path.
  • File names. For ASCII codes the default file name is the same slug PHP produces. For other text the port transliterates Latin-1 and Latin Extended-A letters (é to e, ß to ss, Ø to o, Ł to l, Œ to oe) and drops letters of other scripts: the slug of Straße 界 is strasse. Other scripts can produce different names from PHP. The parity fixtures cover ASCII names only.

Use trusted application assets with LogoBytes. Image decoding is bounded by the package's byte and pixel limits.

Matrix symbols. QR Code, Data Matrix and PDF417 can have a different module grid from PHP's, because each implementation chooses the QR mask, the compaction modes and the symbol size itself (PHP's own QR output changes from run to run). Given the same grid, SVG and HTML are byte-identical to PHP's; tests render the grids recorded from PHP and compare the bytes. The tests use separate decoder paths to check that each Go symbol reads back as the input, with the requested error correction and Macro PDF417 fields.

design/SPEC.md, section 9, specifies every difference in full, including the stricter input checks for retail, postal, Pharmacode and GS1-128 codes, the validated matrix parameters and Macro PDF417.

Provenance

This package is an independent implementation of the behaviour of milon/barcode, which is licensed under LGPL-3.0. It was written from public specifications and from the observed behaviour of the PHP package, and contains no code from it. The parity fixtures are outputs recorded by running the PHP package.

Nobody who writes code for this package reads, copies, translates or adapts the PHP package's source files or its tests. The specification (design/SPEC.md) was written by people who read them; the implementation is written by people who work only from the specification, the public barcode standards, the PHP package's documentation, the recorded output, and third-party implementations under MIT, BSD or Apache-2.0 licences (read, depended on with a reason, or copied under their licence with a provenance header and a notice in NOTICE). Section 0.1 of the specification has the details.

Installation and configuration

go get github.com/bowerbird-si/laravel-go-barcode

The root package needs no configuration: build a generator with barcode.New1D or barcode.New2D and its options. For Laravel for Go, add laravelbarcode.New(...) to the application's packages; it takes the default render options and, for stored files, an existing directory and its public URL. The guide has both.

Compatibility

Module Framework Go
github.com/bowerbird-si/laravel-go-barcode go.laravel.com v0.2.0 1.27.0

36 tests · 205 PHP fixtures · 11 fuzz targets (counted by kit readme)

Contributing

Issues and pull requests are welcome, of any size: bug reports, failing test cases, docs fixes, new features. Contributions written with AI coding agents are welcome too; please say what you checked. Run scripts/kit ci before opening a pull request, and see CONTRIBUTING.md. If you aren't sure, open an issue first.

Credits

Follows the behaviour of milon/barcode; see Provenance.

Status and licence

Maintenance status: active. MIT licensed, see LICENSE.

Community package, not affiliated with Laravel.

Documentation

Overview

Package barcode is a Go port of milon/barcode: generate 1D and 2D barcodes as SVG, HTML and PNG, and 1D barcodes as JPEG, for Go and Laravel for Go.

Upstream: https://github.com/milon/barcode

Example
generator, err := barcode.New1D(barcode.InlineSVG(true), barcode.Padding(10))
if err != nil {
	panic(err)
}
svg, err := generator.SVG("SKU-1042", barcode.C128)
if err != nil {
	panic(err)
}
qr, err := barcode.QR(barcode.QRErrorCorrection(barcode.QRHigh))
if err != nil {
	panic(err)
}
uri, err := (barcode.Generator2D{}).DataURI("https://example.test/item/7", qr, barcode.PNGFormat)
if err != nil {
	panic(err)
}
fmt.Println(strings.HasPrefix(string(svg), "<svg "))
fmt.Println(strings.HasPrefix(uri, "data:image/png;base64,"))
Output:
true
true

Index

Examples

Constants

View Source
const MaxInputBytes = 16384

MaxInputBytes is the largest input accepted for matrix encoding.

View Source
const MaxLinearInputBytes = 1024

MaxLinearInputBytes is the largest input accepted by Encode for a linear symbol.

View Source
const MaxLogoBytes = 16777216

MaxLogoBytes is the largest accepted encoded logo.

View Source
const MaxLogoPixels = 16777216

MaxLogoPixels is the largest accepted logo area.

View Source
const MaxLogoSide = 4096

MaxLogoSide is the largest accepted logo dimension.

View Source
const MaxModule = 1024

MaxModule is the maximum module or font size.

View Source
const MaxPixels = 67108864

MaxPixels is the maximum area of a raster canvas.

View Source
const MaxSide = 16384

MaxSide is the maximum canvas width or height.

View Source
const MaxSpecBytes = 4096

MaxSpecBytes bounds a matrix symbology specification before parsing.

View Source
const Version = "0.1.0"

Version is the version of this module.

Variables

View Source
var (
	// ErrUnsupportedType indicates an unknown symbology.
	ErrUnsupportedType = errors.New("unsupported barcode type")
	// ErrInvalidCode indicates data that cannot be encoded in the selected symbology.
	ErrInvalidCode = errors.New("invalid barcode data")
	// ErrDataTooLong indicates data beyond the input limit or symbol capacity.
	ErrDataTooLong = errors.New("barcode data too long")
)
View Source
var ErrCheckDigit = fmt.Errorf("wrong barcode check digit: %w", ErrInvalidCode)

ErrCheckDigit indicates a supplied digit that does not match the computed digit.

View Source
var ErrInvalidOption = errors.New("invalid barcode option")

ErrInvalidOption indicates an invalid symbology or rendering parameter.

View Source
var ErrTooLarge = errors.New("barcode canvas too large")

ErrTooLarge indicates that the render canvas exceeds a size limit.

View Source
var ErrUnsupportedFormat = errors.New("unsupported barcode format")

ErrUnsupportedFormat indicates that the format cannot carry the requested output.

Functions

This section is empty.

Types

type Bars

type Bars struct {
	// contains filtered or unexported fields
}

Bars is an immutable encoded linear symbol.

func (Bars) All

func (b Bars) All() iter.Seq[Element]

All iterates over the elements from left to right.

func (Bars) Code

func (b Bars) Code() string

Code returns the original input.

func (Bars) Element

func (b Bars) Element(i int) Element

Element returns the indexed element. It panics for an out-of-range index.

func (Bars) Len

func (b Bars) Len() int

Len returns the number of elements, including spaces.

func (Bars) Rows

func (b Bars) Rows() int

Rows returns the symbol's vertical scale.

func (Bars) Width

func (b Bars) Width() int

Width returns the symbol width in modules.

type CheckDigitError

type CheckDigitError struct {
	Type               string
	Expected, Supplied int
}

CheckDigitError reports the expected and supplied retail check digits.

func (*CheckDigitError) Error

func (e *CheckDigitError) Error() string

func (*CheckDigitError) Unwrap

func (e *CheckDigitError) Unwrap() error

Unwrap returns ErrCheckDigit.

type CodeError

type CodeError struct {
	Type   string
	Offset int
	Reason string
	// contains filtered or unexported fields
}

CodeError describes an encoding failure without retaining the caller's data.

func (*CodeError) Error

func (e *CodeError) Error() string

func (*CodeError) Unwrap

func (e *CodeError) Unwrap() error

Unwrap returns the encoding error category.

type Element

type Element struct {
	X, Width    int
	Y, Height   int
	Dark, Guard bool
}

Element is a bar or space in a linear symbol, measured in modules.

type Format

type Format uint8

Format identifies an output format.

const (
	// SVGFormat renders scalable vector markup.
	SVGFormat Format = iota
	// HTMLFormat renders positioned HTML elements.
	HTMLFormat
	// PNGFormat renders a PNG image.
	PNGFormat
	// JPEGFormat renders a JPEG image.
	JPEGFormat
)

func (Format) ContentType

func (f Format) ContentType() string

ContentType returns the MIME type for a supported format.

type Generator1D

type Generator1D struct {
	// contains filtered or unexported fields
}

Generator1D encodes linear barcodes.

func New1D

func New1D(opts ...Option1D) (Generator1D, error)

New1D creates a linear generator with the supplied render options.

func (Generator1D) Base64

func (g Generator1D) Base64(code string, t Type1D, f Format) (string, error)

Base64 returns the base64 encoding of a raster barcode.

func (Generator1D) DataURI

func (g Generator1D) DataURI(code string, t Type1D, f Format) (string, error)

DataURI returns a base64 data URI with the rendered barcode.

func (Generator1D) Encode

func (Generator1D) Encode(code string, typ Type1D) (Bars, error)

Encode encodes a linear symbol, as used by PHP's DNS1D render methods.

func (Generator1D) Generate

func (g Generator1D) Generate(code string, t Type1D, f Format) ([]byte, error)

Generate encodes and renders a linear barcode.

func (Generator1D) HTML

func (g Generator1D) HTML(code string, t Type1D) ([]byte, error)

HTML encodes and renders a HTML barcode.

func (Generator1D) JPEG

func (g Generator1D) JPEG(code string, t Type1D) ([]byte, error)

JPEG encodes and renders a JPEG barcode.

func (Generator1D) PNG

func (g Generator1D) PNG(code string, t Type1D) ([]byte, error)

PNG encodes and renders a PNG barcode.

func (Generator1D) Render

func (g Generator1D) Render(b Bars, f Format) ([]byte, error)

Render converts an encoded linear barcode to the given format.

func (Generator1D) SVG

func (g Generator1D) SVG(code string, t Type1D) ([]byte, error)

SVG encodes and renders a SVG barcode.

func (Generator1D) Save

func (g Generator1D) Save(path, code string, t Type1D, f Format) error

Save atomically writes a barcode to a file in an existing directory.

func (Generator1D) With

func (g Generator1D) With(opts ...Option1D) (Generator1D, error)

With returns a copy with the supplied render options applied in order.

func (Generator1D) WriteTo

func (g Generator1D) WriteTo(w io.Writer, code string, t Type1D, f Format) error

WriteTo writes the rendered barcode to w.

type Generator2D

type Generator2D struct {
	// contains filtered or unexported fields
}

Generator2D encodes matrix barcodes.

func New2D

func New2D(opts ...Option2D) (Generator2D, error)

New2D creates a matrix generator with the supplied render options.

func (Generator2D) Base64

func (g Generator2D) Base64(code string, t Type2D, f Format) (string, error)

Base64 returns the base64 encoding of a raster barcode.

func (Generator2D) DataURI

func (g Generator2D) DataURI(code string, t Type2D, f Format) (string, error)

DataURI returns a base64 data URI with the rendered barcode.

func (Generator2D) Encode

func (Generator2D) Encode(code string, typ Type2D) (Matrix, error)

Encode encodes a matrix symbol, as used by PHP's DNS2D render methods.

func (Generator2D) Generate

func (g Generator2D) Generate(code string, t Type2D, f Format) ([]byte, error)

Generate encodes and renders a matrix barcode.

func (Generator2D) HTML

func (g Generator2D) HTML(code string, t Type2D) ([]byte, error)

HTML encodes and renders a HTML barcode.

func (Generator2D) PNG

func (g Generator2D) PNG(code string, t Type2D) ([]byte, error)

PNG encodes and renders a PNG barcode.

func (Generator2D) Render

func (g Generator2D) Render(m Matrix, f Format) ([]byte, error)

Render converts an encoded matrix barcode to SVG, HTML or PNG.

func (Generator2D) SVG

func (g Generator2D) SVG(code string, t Type2D) ([]byte, error)

SVG encodes and renders a SVG barcode.

func (Generator2D) Save

func (g Generator2D) Save(path, code string, t Type2D, f Format) error

Save atomically writes a barcode to a file in an existing directory.

func (Generator2D) With

func (g Generator2D) With(opts ...Option2D) (Generator2D, error)

With returns a copy with the supplied render options applied in order.

func (Generator2D) WriteTo

func (g Generator2D) WriteTo(w io.Writer, code string, t Type2D, f Format) error

WriteTo writes the rendered barcode to w.

type MacroField

type MacroField interface {
	// contains filtered or unexported methods
}

MacroField is an optional PDF417 Macro metadata field.

func Addressee

func Addressee(v string) MacroField

Addressee sets the Macro addressee.

func Checksum

func Checksum(v int) MacroField

Checksum sets the Macro checksum.

func FileName

func FileName(v string) MacroField

FileName sets the Macro file name.

func FileSize

func FileSize(v int64) MacroField

FileSize sets the Macro file size.

func SegmentCount

func SegmentCount(v int) MacroField

SegmentCount sets the optional Macro segment count.

func Sender

func Sender(v string) MacroField

Sender sets the Macro sender.

func TimeStamp

func TimeStamp(v int64) MacroField

TimeStamp sets the Macro timestamp.

type Matrix

type Matrix struct {
	// contains filtered or unexported fields
}

Matrix is an immutable encoded matrix symbol.

func (Matrix) At

func (m Matrix) At(x, y int) bool

At reports whether the given cell is dark. Coordinates outside the matrix are clear.

func (Matrix) Height

func (m Matrix) Height() int

Height returns the number of rows.

func (Matrix) Type

func (m Matrix) Type() Type2D

Type returns the symbology of the matrix.

func (Matrix) Width

func (m Matrix) Width() int

Width returns the number of columns.

type Option

type Option interface {
	Option1D
	Option2D
}

Option configures either kind of generator.

func Background

func Background(c color.NRGBA) Option

Background fills PNG's otherwise transparent canvas with an opaque color.

func Foreground

func Foreground(c color.NRGBA) Option

Foreground sets the bar or cell color.

func ForegroundCSS

func ForegroundCSS(value string) Option

ForegroundCSS sets a named, hexadecimal, or rgb() foreground color.

func InlineSVG

func InlineSVG(inline bool) Option

InlineSVG omits the XML declaration and doctype when enabled.

func Padding

func Padding(p int) Option

Padding sets the blank margin around the barcode in pixels.

type Option1D

type Option1D interface {
	// contains filtered or unexported methods
}

Option1D configures a linear generator.

func BarWidth

func BarWidth(w float64) Option1D

BarWidth sets the width of one linear module in pixels.

func FontSize

func FontSize(size int) Option1D

FontSize sets the font size of the HTML label.

func Height

func Height(h float64) Option1D

Height sets the linear content height in pixels.

func ShowCode

func ShowCode(show bool) Option1D

ShowCode controls whether the human-readable label is drawn.

type Option2D

type Option2D interface {
	// contains filtered or unexported methods
}

Option2D configures a matrix generator.

func Logo(src image.Image, fraction float64) Option2D

Logo adds a copied, in-memory logo to matrix PNG output.

func LogoBytes

func LogoBytes(data []byte, fraction float64) Option2D

LogoBytes decodes and copies a PNG, JPEG or GIF logo for matrix PNG output.

func ModuleSize

func ModuleSize(w, h float64) Option2D

ModuleSize sets the matrix column width and row height in pixels.

type PDF417ECLevel

type PDF417ECLevel int

PDF417ECLevel selects a PDF417 error correction level.

const (
	// PDF417Auto chooses a correction level based on input size.
	PDF417Auto PDF417ECLevel = iota - 1
	// PDF417EC0 selects correction level 0.
	PDF417EC0
	// PDF417EC1 selects correction level 1.
	PDF417EC1
	// PDF417EC2 selects correction level 2.
	PDF417EC2
	// PDF417EC3 selects correction level 3.
	PDF417EC3
	// PDF417EC4 selects correction level 4.
	PDF417EC4
	// PDF417EC5 selects correction level 5.
	PDF417EC5
	// PDF417EC6 selects correction level 6.
	PDF417EC6
	// PDF417EC7 selects correction level 7.
	PDF417EC7
	// PDF417EC8 selects correction level 8.
	PDF417EC8
)

type PDF417Option

type PDF417Option interface {
	// contains filtered or unexported methods
}

PDF417Option configures PDF417 encoding.

func AspectRatio

func AspectRatio(ratio float64) PDF417Option

AspectRatio sets the PDF417 target width-to-height ratio.

func Macro

func Macro(total, index, fileID int, fields ...MacroField) PDF417Option

Macro sets the PDF417 segment identifiers and optional metadata.

func PDF417ErrorCorrection

func PDF417ErrorCorrection(level PDF417ECLevel) PDF417Option

PDF417ErrorCorrection selects the equivalent of PHP's PDF417 correction field.

type QRLevel

type QRLevel int

QRLevel identifies a QR error correction level.

const (
	// QRLow is PHP's default QR correction level (L).
	QRLow QRLevel = iota
	// QRMedium is QR correction level M.
	QRMedium
	// QRQuartile is QR correction level Q.
	QRQuartile
	// QRHigh is QR correction level H.
	QRHigh
)

type QROption

type QROption interface {
	// contains filtered or unexported methods
}

QROption configures QR encoding.

func QRErrorCorrection

func QRErrorCorrection(level QRLevel) QROption

QRErrorCorrection selects the equivalent of PHP's QRCODE level field.

type Type1D

type Type1D int

Type1D identifies a linear symbology.

const (

	// C39 selects the PHP C39 symbology.
	C39 Type1D
	// C39Plus selects the PHP C39+ symbology.
	C39Plus
	// C39E selects the PHP C39E symbology.
	C39E
	// C39EPlus selects the PHP C39E+ symbology.
	C39EPlus
	// C93 selects the PHP C93 symbology.
	C93
	// S25 selects the PHP S25 symbology.
	S25
	// S25Plus selects the PHP S25+ symbology.
	S25Plus
	// I25 selects the PHP I25 symbology.
	I25
	// I25Plus selects the PHP I25+ symbology.
	I25Plus
	// C128 selects the PHP C128 symbology.
	C128
	// C128A selects the PHP C128A symbology.
	C128A
	// C128B selects the PHP C128B symbology.
	C128B
	// C128C selects the PHP C128C symbology.
	C128C
	// GS1128 selects the PHP GS1-128 symbology.
	GS1128
	// EAN2 selects the PHP EAN2 symbology.
	EAN2
	// EAN5 selects the PHP EAN5 symbology.
	EAN5
	// EAN8 selects the PHP EAN8 symbology.
	EAN8
	// EAN13 selects the PHP EAN13 symbology.
	EAN13
	// UPCA selects the PHP UPCA symbology.
	UPCA
	// UPCE selects the PHP UPCE symbology.
	UPCE
	// MSI selects the PHP MSI symbology.
	MSI
	// MSIPlus selects the PHP MSI+ symbology.
	MSIPlus
	// POSTNET selects the PHP POSTNET symbology.
	POSTNET
	// PLANET selects the PHP PLANET symbology.
	PLANET
	// RMS4CC selects the PHP RMS4CC symbology.
	RMS4CC
	// KIX selects the PHP KIX symbology.
	KIX
	// IMB selects the PHP IMB symbology.
	IMB
	// Codabar selects the PHP CODABAR symbology.
	Codabar
	// Code11 selects the PHP CODE11 symbology.
	Code11
	// Pharma selects the PHP PHARMA symbology.
	Pharma
	// Pharma2T selects the PHP PHARMA2T symbology.
	Pharma2T
)

func ParseType1D

func ParseType1D(name string) (Type1D, error)

ParseType1D parses a PHP symbology name, ignoring ASCII letter case.

func (Type1D) String

func (t Type1D) String() string

String returns the PHP symbology name, or an empty string for an invalid value.

type Type2D

type Type2D interface {
	String() string
	// contains filtered or unexported methods
}

Type2D is a matrix symbology and its encoding parameters.

func DataMatrix

func DataMatrix() Type2D

DataMatrix constructs the DATAMATRIX symbology (ECC 200).

func PDF417

func PDF417(opts ...PDF417Option) (Type2D, error)

PDF417 constructs a PDF417 symbology with the supplied options.

func ParseType2D

func ParseType2D(spec string) (Type2D, error)

ParseType2D parses a PHP matrix symbology specification.

func QR

func QR(opts ...QROption) (Type2D, error)

QR constructs a QRCODE symbology with the supplied options.

Directories

Path Synopsis
Package laravelbarcode integrates barcode generators and storage with Laravel for Go.
Package laravelbarcode integrates barcode generators and storage with Laravel for Go.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL