Question

I need to generate formatted text packing slips for a Ruby on Rails project I'm working on. I'm considering using Ruport or just formatting it myself in a string and outputting it to text. The only challenge is justifying all of the output appropriately. It needs to look something like this, always aligned properly. Any recommendations?

Company Name
(T) 1-800-123-1234
(E) info@company.com

BILL TO: CUSTOMER NAME                   SHIP TO: CUSTOMER NAME
123 Some Street                          321 Some Street
Address etc.                             Address etc.

Date: 2010-03-12 16:30
Payment Number: 1234-123456

LN  NAME             SKU           DESCRIPTION             QTY    PRICE      TOTAL
----------------------------------------------------------------------------------
001 Product name     GUDB 012 HGQ  product description     2      52.99     105.98
         - Color
Was it helpful?

Solution

As FM already suggested, you can use sprintf:

"%10s %-10s %10s" % ['abc', 'def', 'ghi'] # use negative numbers for left alignment
#=> "       abc def               ghi"

And if you need something more sophisticated, try using some standard templating engine, such as erb...

OTHER TIPS

If your output format is HTML, use CSS to make a print-media stylesheet. This layout would be relatively easy to make that way.

If you're outputting monospaced text, use spaces to format everything. You may have to track how much whitespace you have used. This ensures you can simply insert the due number of spaces to the next block.

EDIT: I didn't see the comment about needing to generate text files until after I wrote this. I'm going to leave it up for a bit before deleting it, in case it turns out to be useful.


Ruport may be overkill. Prawn is a PDF writer library by the same author that is very lightweight and easy to use. (Much easier than the old PDF::Writer library that Ruport uses. In fact, Gregory Brown wrote Prawn with the specific goal to replace to PDF::Writer in Ruport.)

I even remember that someone create a lightweight templating engine for Prawn, but unfortunately I don't remember who that was or what it's called. But the Prawn mailinglist and IRC channel are extremely friendly and helpful, they probably know.

Since you are using Rails, you might also be interested in the Prawnto Rails plugin, which registers Prawn as a view engine in Rails, and allows you to render your PDFs the exact same way you render your HTML. There's also a Railscast which covers Prawn and Prawnto and a corresponding ASCIIcast.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top