Getting started

laravel-go-barcode Alpha Laravel for Go

This page shows how to install laravel-go-barcode, render barcodes in each format, and use it in Laravel for Go.

Install

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

The module needs Go 1.27. The laravelbarcode subpackage needs go.laravel.com v0.2.0.

A linear barcode

A generator holds the render settings. Build one with barcode.New1D, then render a code with a symbology:

package main

import (
	"log"
	"os"

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

func main() {
	gen, err := barcode.New1D(barcode.BarWidth(2), barcode.Height(40), barcode.Padding(10))
	if err != nil {
		log.Fatal(err)
	}
	svg, err := gen.SVG("SKU-1042", barcode.C128)
	if err != nil {
		log.Fatal(err)
	}
	os.Stdout.Write(svg)
}

Generators are immutable values and safe for concurrent use. With returns a copy with more options; the zero value barcode.Generator1D{} uses the defaults.

red, err := gen.With(barcode.ForegroundCSS("#c00"), barcode.ShowCode(false))

Symbologies

Each symbology is a Type1D constant. ParseType1D takes the PHP name, ignoring ASCII case, and String returns it.

ConstantPHP nameSymbology
C39, C39PlusC39, C39+Code 39, without and with check character
C39E, C39EPlusC39E, C39E+Code 39 Full ASCII, without and with check character
C93C93Code 93
S25, S25PlusS25, S25+Standard 2 of 5, without and with check digit
I25, I25PlusI25, I25+Interleaved 2 of 5, without and with check digit
C128C128Code 128, automatic subset selection
C128A, C128B, C128CC128A, C128B, C128CCode 128, fixed subset
GS1128GS1-128GS1-128, input such as (01)09501101530003(10)ABC123
EAN2, EAN5EAN2, EAN5EAN/UPC add-ons
EAN8, EAN13, UPCA, UPCEEAN8, EAN13, UPCA, UPCERetail codes, with the split-digit layout
MSI, MSIPlusMSI, MSI+MSI (Modified Plessey), without and with check digit
POSTNET, PLANETPOSTNET, PLANETUSPS POSTNET and PLANET
RMS4CC, KIXRMS4CC, KIXRoyal Mail 4-State Customer Code, Dutch KIX
IMBIMBUSPS Intelligent Mail Barcode
Codabar, Code11CODABAR, CODE11Codabar, Code 11
Pharma, Pharma2TPHARMA, PHARMA2TPharmacode, one-track and two-track
typ, err := barcode.ParseType1D("c39e+") // barcode.C39EPlus

For EAN-8, EAN-13 and UPC-A you may leave out the check digit; when you supply it and it is wrong, the error is a *barcode.CheckDigitError with the expected and supplied digits.

The retail types print their digits in groups below shorter data bars. With the digits shown, the height must be at least 31 in SVG, 33 in HTML at the default font size, and 39 in PNG. SVG shows them by default, so the default height of 30 is ErrInvalidOption for EAN8, EAN13, UPCA and UPCE in SVG: set Height(40) or ShowCode(false). The same check applies to other types: the text must leave at least one pixel of bar.

Output formats

MethodReturns
SVG(code, typ)SVG document; with InlineSVG(true) without the XML declaration and doctype
HTML(code, typ)Absolutely positioned div elements
PNG(code, typ)PNG bytes, transparent unless a background is set
JPEG(code, typ)JPEG bytes on white (linear symbols only)
Generate(code, typ, format)Any of the above, chosen with SVGFormat, HTMLFormat, PNGFormat or JPEGFormat
Base64(code, typ, format)Base64 of a PNG or JPEG without a prefix, as PHP's getBarcodePNG returns
DataURI(code, typ, format)data:<content type>;base64,… for any format
WriteTo(w, code, typ, format)Writes the output to an io.Writer
Save(path, code, typ, format)Writes the file atomically, mode 0644, into an existing directory
Encode(code, typ) and Render(symbol, format)Encode once, render in several formats

Format.ContentType() gives the MIME type for an HTTP response: image/svg+xml, text/html; charset=utf-8, image/png or image/jpeg.

png, err := gen.PNG("4006381333931", barcode.EAN13)
uri, err := gen.DataURI("SKU-1042", barcode.C128, barcode.PNGFormat) // for an <img src>
err = gen.Save("/var/www/labels/sku-1042.png", "SKU-1042", barcode.C128, barcode.PNGFormat)

Save writes the path as given and creates no directory.

Options

Options apply in order; when two set the same thing, the later one wins.

OptionApplies toDefault
BarWidth(w)linear2 pixels per module
Height(h)linear30 pixels, including the text
ShowCode(bool)lineartext shown in SVG, hidden in HTML, PNG and JPEG (as in PHP)
FontSize(n)linear, HTML text12
ModuleSize(w, h)matrix3 × 3 for SVG and PNG, 10 × 10 for HTML
Padding(p)both0; a negative value is an error
Foreground(color.NRGBA)bothblack
ForegroundCSS(s)botha CSS colour name, #rgb, #rrggbb or rgb(r, g, b)
Background(color.NRGBA)both, PNG onlytransparent; must be opaque
InlineSVG(bool)both, SVG onlyoff
Logo(img, fraction), LogoBytes(data, fraction)matrix, PNG onlynone

ForegroundCSS writes the colour into SVG and HTML exactly as you give it and uses its RGB value for PNG and JPEG. PNG and JPEG need an opaque foreground. A value outside the limits is barcode.ErrInvalidOption.

Matrix barcodes

Matrix symbologies are Type2D values, built by functions that validate their parameters:

qr, err := barcode.QR(barcode.QRErrorCorrection(barcode.QRHigh)) // QRLow is the default
dm := barcode.DataMatrix()
pdf, err := barcode.PDF417(
	barcode.AspectRatio(3),
	barcode.PDF417ErrorCorrection(barcode.PDF417EC5), // PDF417Auto is the default
)

Render them with a Generator2D:

gen, err := barcode.New2D(barcode.ModuleSize(4, 4), barcode.Padding(8))
if err != nil {
	return err
}
svg, err := gen.SVG("https://example.test/item/7", qr)
png, err := gen.PNG("https://example.test/item/7", qr)

Matrix symbols render as SVG, HTML and PNG. JPEG is barcode.ErrUnsupportedFormat.

PHP's type strings work too. ParseType2D reads them and String writes them back:

typ, err := barcode.ParseType2D("PDF417,3,5") // aspect 3, error correction level 5
fmt.Println(typ)                               // PDF417,3,5

Macro PDF417

A large document can be split over several PDF417 symbols. Macro(total, index, fileID, fields...) sets the segment; the optional fields are FileName, SegmentCount, TimeStamp, Sender, Addressee, FileSize and Checksum.

first, err := barcode.PDF417(barcode.Macro(2, 0, 1, barcode.FileName("report.pdf")))
fmt.Println(first) // PDF417,,,2,0,1,report.pdf

The file ID is a number from 0 to 899, and the index runs from 0 to total − 1. The last segment carries the final-segment marker.

Logo and LogoBytes put a logo in a white box in the centre of a matrix PNG. The fraction is the logo's share of the canvas width, clamped to 5 to 35 percent. LogoBytes accepts PNG, JPEG and GIF. The logo comes from memory; nothing is read from a path or fetched.

logo, err := os.ReadFile("logo.png")
if err != nil {
	return err
}
withLogo, err := gen.With(barcode.LogoBytes(logo, 0.2))
png, err := withLogo.PNG("https://example.test", qr)

Use a high QR error correction level with a logo and scan-test the final image. A larger overlay can make a symbol unreadable even at the highest level.

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. Use ShowCode(false) for a shorter barcode.

Encoded symbols

Encode gives the symbol without rendering it. Bars lists the bars and spaces of a linear symbol (Width, Rows, Len, Element(i), All()), and Matrix gives the cells of a matrix symbol (Width, Height, At(x, y)). Render turns either into any format with the generator's settings.

bars, err := gen.Encode("SKU-1042", barcode.C128)
svg, err := gen.Render(bars, barcode.SVGFormat)
png, err := gen.Render(bars, barcode.PNGFormat)

Errors

Every error matches one of these with errors.Is:

ErrorWhen
ErrUnsupportedTypean unknown symbology name
ErrInvalidCodedata the symbology cannot encode; a *CodeError gives the type, the byte offset and the reason, never the data
ErrCheckDigita wrong retail check digit (*CheckDigitError, wraps ErrInvalidCode)
ErrDataTooLonginput over 1024 bytes (linear) or 16384 bytes (matrix), or over the symbol's capacity
ErrInvalidOptionan option or symbology parameter out of range
ErrUnsupportedFormatJPEG for a matrix symbol, a logo outside PNG, or storing SVG or HTML
ErrTooLargea canvas over MaxSide (16384) pixels on a side or MaxPixels in total
_, err := gen.SVG("4006381333932", barcode.EAN13)
var cd *barcode.CheckDigitError
if errors.As(err, &cd) {
	fmt.Println(cd.Expected, cd.Supplied) // 1 2
}

Laravel for Go

The laravelbarcode package installs the generators in the application. Its options set the defaults for every barcode the application renders, and where stored files go:

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

barcodes, err := laravelbarcode.New(
	laravelbarcode.Linear(barcode.BarWidth(2), barcode.Height(40)),
	laravelbarcode.Matrix(barcode.ModuleSize(4, 4)),
	laravelbarcode.StoreDir("storage/app/public/barcodes"),
	laravelbarcode.StoreURL("/storage/barcodes"),
)
if err != nil {
	return err
}

app, err := laravel.New(laravel.Options{
	// …
	Packages: []laravel.Package{barcodes},
})

StoreDir must name an existing directory. StoreURL takes an absolute http or https URL, or a path starting with one /. Both are optional; without StoreDir, storing returns laravelbarcode.ErrNoStore. The zero laravelbarcode.Package{} uses default settings and no store.

Templates

Six template functions take the code, a PHP type name or type string, and optional render options:

FunctionOutput
barcode1D, barcode2DInline SVG (always without the XML declaration)
barcode1DHTML, barcode2DHTMLHTML
barcode1DSrc, barcode2DSrcA PNG data URI for <img src>
{{ barcode1D "SKU-1042" "C128" }}
{{ barcode1DHTML "4006381333931" "EAN13" }}
<img src="{{ barcode2DSrc "https://example.test/item/7" "QRCODE,H" }}" alt="QR code">

The output is marked safe for the template, so it is not escaped again; the label text inside it is escaped by the package.

Responses

Response1D and Response2D render with the application's defaults plus per-call options, and return a response with status 200 and the format's content type:

router.Get("/barcode.png", func(r *web.Request) *web.Response {
	resp, err := laravelbarcode.Response1D(r.Context(), "SKU-1042", barcode.C128, barcode.PNGFormat)
	if err != nil {
		return web.Fail(err)
	}
	return resp
})

From1D(ctx) and From2D(ctx) return the application's generators for anything else.

Storing files

Store1D, StoreAs1D, Store2D and StoreAs2D render a barcode and write it into the store directory. Linear symbols store as PNG or JPEG, matrix symbols as PNG. The result has the file name, its absolute path and its public URI (empty without StoreURL).

stored, err := laravelbarcode.Store1D(ctx, "SKU 1042", barcode.C128, barcode.PNGFormat)
// stored.Name == "sku-1042.png", stored.URI == "/storage/barcodes/sku-1042.png"

stored, err = laravelbarcode.StoreAs2D(ctx, "labels/item-7.png", "https://example.test/item/7",
	barcode.DataMatrix(), barcode.PNGFormat)
// stored.Name == "item-7.png"

File names:

  • The default name is a slug of the code, or for matrix symbols of the code followed by the type string: DM-URI-1 as Data Matrix becomes dm-uri-1datamatrix.png. The slug lowercases ASCII letters and digits, writes @ as at, joins words with - and drops other punctuation.
  • Latin-1 and Latin Extended-A letters are transliterated (é to e, ß to ss, Ø to o, Ł to l, Œ to oe). Letters of other scripts are dropped. A code that leaves an empty slug needs a custom name.
  • A custom name keeps only its last path segment (after / or \), loses one .png, .jpg or .jpeg extension, and gets the format's extension. Names with control characters, <>:"|?*, a trailing dot or space, or a Windows device name such as CON are rejected with ErrInvalidOption.
  • The same name overwrites the same file.

Every write stays inside the store directory: the file is written to a temporary file and renamed over the target, so a reader never sees half a file. The stored bytes are the same as the in-memory output for the same symbol and options.

Supply custom basenames from trusted application code. If a web server serves the storage directory, configure it to serve files as static content.