(Physically) Printing with Ruby!

Recently, we were asked to develop an application that would silently print to a physical printer (in this case, a Zebra ZR203) on a Windows computer. The aim of the program was to use it to print coupons in conjunction with a touch screen computer.

One way we considered doing this was by using the Zebra Programming Language (ZPL) to create the label, connect the Zebra printer to the LAN, and sending it to TCP port 9100 on the printer. However, this method could get very messy when deploying the finished product to dozens of locations. We needed the setup to be as trouble-free as possible.

I found Foxit, a (Windows only) PDF reader, which conveniently allows for command line printing. Together with the great PDF generator gem, Prawn, I generated a PDF from the coupon PNG image:

Prawn::Document.generate("coupon.pdf", :page_size => [225, 1132], :margin => [0,0,0,0]) do |pdf|
    pdf.image("coupon.png", :fit => [225, 1132])
end

and executed a system command using Ruby’s “system” command:

    system(""C:\Program Files (x86)\Foxit Software\Foxit Reader\Foxit Reader.exe" /t "coupon.pdf"")

Of course this command depends on the install location of Foxit, but Program Files (x86) is the default location. This command will print to the current default printer, but you can specifiy a printer by appending its name to the end of the command like so:

   system(""C:\Program Files (x86)\Foxit Software\Foxit Reader\Foxit Reader.exe" /t "coupon.pdf" "#{printerName}" ")

Finally, we had this small application running locally with Sinatra, and had the frontend perform Ajax GET requests to the backend:

$.get('http://localhost:4567/print', (data) ->)

And that’s it!

Leave a Reply

wpDiscuz