Tuesday, March 1, 2011

Generate PDF from Rails

The Ruby On Rails Wiki lists a couple of libraries that facilitate PDF generation in Rails. I need to print out address labels (in letter format, thus 12-15 addresses per page) and cannot decide which one to use. Any recommendations?

From stackoverflow
  • The best I've seen so far is Prawn:

    Sebastian : thx! Prawn seems to be the way to go....especially with the prawnto plugin it's really easy to use
  • I've used both PDF::Writer and Prawn and find Prawn much more pleasant to use. Check out Ruby Mendicant for a comparison that demonstrates the joys of Prawn w/r/t PDF::Writer.

    Actually, just check out Ruby Mendicant anyway for a great design pattern for right livelihood as a developer.

  • There's also RTeX. That works well if you're willing to translate to LaTeX first. LaTeX is a very good way to store marked-up documents. It just depends on how static each document is. If most of the document is dynamic, you might do better with Prawn or PDF::Writer. If most of it is static, with just a couple of text-replacements for each, LaTeX might be a better choice.

  • Prawn with Prawnto for sure. The DSL is a real treat, as is the simplicity of being able to treat PDF as any other format in a respond_to format block:

    respond_to do |format|
    format.pdf { render :layout => false }
    

    I'm not sure whether PDF::Writer is as elegant. I wrote a very basic tutorial on Prawn and Prawnto for Rails beginners here:

    ARemesal : An excellent tutorial for first steps with Prawn, thx :)
  • Prawn is the way to go. Now with prawn-grids it is really easy to do.

    Check out the fill article here:

    http://www.ducksoupsoftware.com/blog/200907/rails_labels.html

    The code example from the site:

    ## Controller
    prawnto :prawn => {:left_margin => 0.21975.in, 
                       :right_margin => 0.21975.in}
    
    ## View
    pdf.define_grid(:columns => 3, :rows => 10, :column_gutter => 10)
    
    pdf.grid.rows.times do |i|
      pdf.grid.columns.times do |j|
        b = pdf.grid(i,j)
        pdf.bounding_box b.top_left, :width => b.width, :height => b.height do
          pdf.text b.name
          pdf.stroke do
            pdf.rectangle(pdf.bounds.top_left, b.width, b.height)
          end
        end
      end
    end
    
  • Though not completely ruby, you could use OpenOffice .odt to generate PDFs by combining serenity and docsplit.

    http://github.com/kremso/serenity

    http://documentcloud.github.com/docsplit/

    Or you could use the clamsy gem which uses odt and cups-pdf to generate the PDF.

    http://github.com/ngty/clamsy

0 comments:

Post a Comment