# Getting started (laravel-go-barcode)

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

- Package: laravel-go-barcode (Laravel for Go, alpha), go modules: `github.com/bowerbird-si/laravel-go-barcode`
- Maintenance: active; Latest release: 0.1.0 (2026-12-05); Framework: go.laravel.com v0.2.0 or later; Go: Go 1.27.0 or later; Licence: MIT
- Links: [Repository](https://github.com/bowerbird-si/laravel-go-barcode), [pkg.go.dev](https://pkg.go.dev/github.com/bowerbird-si/laravel-go-barcode@v0.1.0), [Changelog](https://oss.bowerbird.si/go-barcode/docs/changelog/), [Contributing](https://github.com/bowerbird-si/laravel-go-barcode/blob/5efb0cf6740c5e82e000c53b2d1f67d375f7960e/CONTRIBUTING.md), [Security policy](https://github.com/bowerbird-si/laravel-go-barcode/blob/5efb0cf6740c5e82e000c53b2d1f67d375f7960e/SECURITY.md)
- Based on: [milon/barcode](https://github.com/milon/barcode): Reference behaviour for this independent Go implementation, following version 13.6.0.
- PHP parity: full (62 covered, 13 diverged, 0 planned of 75 abilities; 205 fixtures; follows milon/barcode v13.6.0; verified 2026-12-05)
- Community package, not affiliated with Laravel.
- HTML version: https://oss.bowerbird.si/go-barcode/docs/getting-started/
- Source: https://github.com/bowerbird-si/laravel-go-barcode/blob/5efb0cf6740c5e82e000c53b2d1f67d375f7960e/docs/getting-started.md

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

## Install

```shellscript
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:

```go
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.

```go
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.

| Constant | PHP name | Symbology |
| --- | --- | --- |
| `C39`, `C39Plus` | `C39`, `C39+` | Code 39, without and with check character |
| `C39E`, `C39EPlus` | `C39E`, `C39E+` | Code 39 Full ASCII, without and with check character |
| `C93` | `C93` | Code 93 |
| `S25`, `S25Plus` | `S25`, `S25+` | Standard 2 of 5, without and with check digit |
| `I25`, `I25Plus` | `I25`, `I25+` | Interleaved 2 of 5, without and with check digit |
| `C128` | `C128` | Code 128, automatic subset selection |
| `C128A`, `C128B`, `C128C` | `C128A`, `C128B`, `C128C` | Code 128, fixed subset |
| `GS1128` | `GS1-128` | GS1-128, input such as `(01)09501101530003(10)ABC123` |
| `EAN2`, `EAN5` | `EAN2`, `EAN5` | EAN/UPC add-ons |
| `EAN8`, `EAN13`, `UPCA`, `UPCE` | `EAN8`, `EAN13`, `UPCA`, `UPCE` | Retail codes, with the split-digit layout |
| `MSI`, `MSIPlus` | `MSI`, `MSI+` | MSI (Modified Plessey), without and with check digit |
| `POSTNET`, `PLANET` | `POSTNET`, `PLANET` | USPS POSTNET and PLANET |
| `RMS4CC`, `KIX` | `RMS4CC`, `KIX` | Royal Mail 4-State Customer Code, Dutch KIX |
| `IMB` | `IMB` | USPS Intelligent Mail Barcode |
| `Codabar`, `Code11` | `CODABAR`, `CODE11` | Codabar, Code 11 |
| `Pharma`, `Pharma2T` | `PHARMA`, `PHARMA2T` | Pharmacode, one-track and two-track |

```go
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

| Method | Returns |
| --- | --- |
| `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`.

```go
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.

| Option | Applies to | Default |
| --- | --- | --- |
| `BarWidth(w)` | linear | 2 pixels per module |
| `Height(h)` | linear | 30 pixels, including the text |
| `ShowCode(bool)` | linear | text shown in SVG, hidden in HTML, PNG and JPEG (as in PHP) |
| `FontSize(n)` | linear, HTML text | 12 |
| `ModuleSize(w, h)` | matrix | 3 × 3 for SVG and PNG, 10 × 10 for HTML |
| `Padding(p)` | both | 0; a negative value is an error |
| `Foreground(color.NRGBA)` | both | black |
| `ForegroundCSS(s)` | both | a CSS colour name, `#rgb`, `#rrggbb` or `rgb(r, g, b)` |
| `Background(color.NRGBA)` | both, PNG only | transparent; must be opaque |
| `InlineSVG(bool)` | both, SVG only | off |
| `Logo(img, fraction)`, `LogoBytes(data, fraction)` | matrix, PNG only | none |

`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:

```go
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`:

```go
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:

```go
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`.

```go
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

`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.

```go
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.

```go
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`:

| Error | When |
| --- | --- |
| `ErrUnsupportedType` | an unknown symbology name |
| `ErrInvalidCode` | data the symbology cannot encode; a `*CodeError` gives the type, the byte offset and the reason, never the data |
| `ErrCheckDigit` | a wrong retail check digit (`*CheckDigitError`, wraps `ErrInvalidCode`) |
| `ErrDataTooLong` | input over 1024 bytes (linear) or 16384 bytes (matrix), or over the symbol's capacity |
| `ErrInvalidOption` | an option or symbology parameter out of range |
| `ErrUnsupportedFormat` | JPEG for a matrix symbol, a logo outside PNG, or storing SVG or HTML |
| `ErrTooLarge` | a canvas over `MaxSide` (16384) pixels on a side or `MaxPixels` in total |

```go
_, 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:

```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:

| Function | Output |
| --- | --- |
| `barcode1D`, `barcode2D` | Inline SVG (always without the XML declaration) |
| `barcode1DHTML`, `barcode2DHTML` | HTML |
| `barcode1DSrc`, `barcode2DSrc` | A PNG data URI for `<img src>` |

```html
{{ 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:

```go
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`).

```go
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.
