Read more

Generating barcodes with the Barby gem

Arne Hartherz
April 11, 2017Software engineer at makandra GmbH

Barby is a great Ruby gem to generate barcodes of all different sorts.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

It includes support for QR codes via rQRCode Show archive.org snapshot ; if you need to render only QR codes, you may want to use that directly.

Example usage

Generating a barcode is simple:

>> Barby::Code128.new('Hello Universe').to_png
=> "\x89PNG\r\n\u001A..."

Configuration

Barby supports several barcode types Show archive.org snapshot and you must require all necessary files explicitly.

For the example above these are barby/barcode/code_128 and barby/outputter/png_outputter.
You can specify that in your Gemfile like so:

gem 'barby', require: %w(barby barby/barcode/code_128 barby/outputter/png_outputter)

Pro tips

  • Barby's PNG outputter uses ChunkyPNG under the hood. You can call to_image to receive a ChunkyPNG::Canvas that you can rotate, resample, or just convert to a data URL.

    >> Barby::Code128.new('Hello Universe').to_image.to_data_url
    => "data:image/png;base64,iVBORw0KGgoAA..."
    
  • For super-crisp barcodes, render them as SVG. Printing images usually causes some level of blur, but SVGs don't. Require Barby's svg_outputter and render an SVG (XML) string:

    svg = Barby::Code128.new('Hello Universe').to_svg(margin: 0)
    

    To make that SVG freely scalable, you need to add preserveAspectRatio="none":

    svg.sub!('<svg ', '<svg preserveAspectRatio="none" ')
    

    Generating a data URI is simple:

    "data:image/svg+xml;utf8,#{svg.gsub(/\n/, '')}"
    
  • See the wiki Show archive.org snapshot for options on outputters and more.

Posted by Arne Hartherz to makandra dev (2017-04-11 11:08)