Printing a file to a printer in Ruby

前端 未结 4 685
清酒与你
清酒与你 2020-12-16 06:29

I need help with sending a formatted text to a printer using Ruby on Ruby on Rails OR sending a pdf file to a printer from Ruby program. I can write the code to create a pdf

4条回答
  •  抹茶落季
    2020-12-16 07:06

    I have an internal app for creating computer labels. I import computers from a file I get from Dell or enter them manually, I export them to a CSV that I can import into MS SCCM. I can print labels to put on computers. The labels have a company logo, the computer name, MAC address and servicedesk contact info.

    I print it with gLabels. You design a label in gLabels, enter dynamic fields and feed a CSV to it and it spits out a PDF which I then use lpr to print to my Dymo Labelwriter.

    I put it in my Computers model because I didn't know where else to put it.

    # Print all computers with printed = false
    def self.print
      printed_labels = 0 
      csv_file = Tempfile.new(["computers", ".csv"])
      logger.debug("Writing #{csv_file.path}")
      begin
        Computer.transaction do
          Computer.unprinted.each do |computer|
            csv_file.puts "\"#{computer.mac(' ')}\",\"#{computer.hostname}\""
            computer.printed = true
            computer.save
            printed_labels += 1
          end
        end 
      ensure
        csv_file.close
        if csv_file.length > 0 
          pdf_file = Tempfile.new(["computers", ".pdf"])
          begin
            pdf_file.close
            system '/usr/bin/glabels-batch', "--input=#{csv_file.path}", "--output=#{pdf_file.path}", AssetBase::Application.config.computer_label
            system '/usr/bin/lpr', '-P', 'LabelWriter-450', pdf_file.path
          ensure
            pdf_file.unlink
          end
        end
        csv_file.unlink
      end   
      printed_labels
    end
    

    This runs on Fedora Linux so the printer backend is CUPS and what part of it that handles PDF I don't know. It could be CUPS or the printer driver or the printer driver itself.

    There are other methods of creating structured text to PDF but for labels gLabels is great.

提交回复
热议问题