Skip to content

Instantly share code, notes, and snippets.

@SingularityMatrix
Created May 30, 2015 15:55
Show Gist options
  • Save SingularityMatrix/265390ba64d08544b58f to your computer and use it in GitHub Desktop.
Save SingularityMatrix/265390ba64d08544b58f to your computer and use it in GitHub Desktop.
Create and annotate barcodes in Ruby
require 'barby'
require 'barby/barcode/code_128'
require 'barby/outputter/png_outputter'
require 'mini_magick'
require 'benchmark'
# Build a sample barcode
def build_barcode(prod, supplier_code, batch_no)
bar_code = prod + "-" + supplier_code + "-"+ batch_no
bar_code_image = bar_code.delete("/") # Clear all /'s in the code if any ..
path = "#{Rails.root}/public/barcodes/#{bar_code_image}.png"
end
# Create a barcode image object like so ..
@barcode_object = Barby::Code128B.new(bar_code)
# Write the barcode image object to a file => barcode png image
File.open(path, 'w') { |f| f.write @barcode_object.to_png(:margin => 35, :xdim => 2,:ydim => 2, :height => 100) }
# Annotate text to barcode image using MiniMagick
def annotate_barcode(path)
img = MiniMagick::Image.open(path)
img.combine_options do |c|
c.font "#{Rails.root}/public/fonts/Calibri.ttf"
c.fill "black"
c.pointsize 20
c.gravity "center"
c.draw "text 0,65 '#{bar_code}'"
end
img.write(path)
end
@SingularityMatrix
Copy link
Author

You can pass more options for annotation. See the mini_magick usage documentation here https://github.com/minimagick/minimagick#usage

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment