nicktabs nicktabs - 3 months ago 47
Ruby Question

Ruby on Rails & Prawn PDF - Create Customer List

I'm trying to produce a PDF report with Prawn, I can get it to do a report on a show action easily enough by passing the single ID but I want to produce one with every record in it. Like a standard rails scaffold index page. Using rails it would look like this:

<% @customer.each do |customer| %>
<%= customer.id %>
<%= customer.name %>
<%end%>


Easy!

But I'm not sure how to do this with Prawn..

Something like:

def index
@customer = Customer.all
respond_to do |format|
format.html
Prawn::Document.generate("customer_list.pdf") do |pdf|
pdf.text "#{@customer.id} "
pdf.text "#{@customer.name} "
end
end
end


Which clearly isn't right.

Any ideas? Thank you.

Answer

It's easy to do with Prawn, Gemfile => gem 'prawn', bundle

lets say you have Customer model:

customers_controller.rb

def show
   @customer = Customer.find(params[:id])
   respond_to do |format|
     format.html
     format.pdf do
        pdf = CustomerPdf.new(@customer)
        send_data pdf.render, filename: "customer_#{id}.pdf",
                              type: "application/pdf",
                              disposition: "inline"
     end
   end
end

then just create pdfs folder under the apps directory, and create file customer_pdf.rb

class CustomerPdf< Prawn::Document

  def initialize(customer)
    super()
    @customer = customer
    text "Id\##{@customer.id}"
    text "Name\##{@customer.name}"
  end

end

show.html.erb

  <div class="pdf_link">
    <%= link_to "E-version", customer_path(@customer, :format => "pdf") %>
  </div>

EDIT:

and don't forget to include pdf to config/initializers/mime_types.rb

Mime::Type.register "application/pdf", :pdf