module Sapos module Print class Printer def initialize(config) @config = config end def print(raw_message) puts "Print =>" filename = SecureRandom.hex result = false raw = raw_message.force_encoding("UTF-8") begin printable = data(raw_message) File.open(filename, 'w'){|f| f.write(printable)} result = send_to_printer({file: filename}) puts "Result: #{result}" rescue => e puts "#{e.message}" self.errors = e.message result = false ensure File.delete(filename) if File.exists?(filename) return result end end def data(raw_message) puts "data: #{@config.interface}" case @config.interface when 'text' return raw_message when 'escp' esc = "\x1B" #ESC byte in hex notation newLine = "\x0A" #LF byte in hex notation cmds = esc + "@" cmds += esc + "!"+"\00" cmds += raw_message cmds += newLine + newLine cmds += "\x1D\x56\x42\x03" # Cut Paper cmds += "\x1B\x70\x00\x19\xFA" # Open drawer return cmds else raise "Unknown interface: #{@config.interface}" end end def send_to_printer(opts = {}) case @config.adapter when 'console' puts "=> CONSOLE: file: #{opts[:file]}<=" puts File.read(opts[:file]) puts "=> END CONSOLE =<" return true when 'cups' file = opts.delete(:file) command_options = [] command_options << "-d #{@printer_name}" command_options << "-o raw" if opts[:raw].present? command = "lp #{command_options.join(" ")} #{file}" puts "CMD => #{command}" if !system(command) puts "Not executed" return false end return true when 'windows' command = "copy #{opts[:file]} "+'"\\\\%COMPUTERNAME%\\'+@config.printer if !system(command) puts "Not executed" return false end return true end end end end end