Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 647
nicktabs Avatar asked Apr 02 '12 18:04

nicktabs


3 Answers

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
like image 164
Said Kaldybaev Avatar answered Oct 05 '22 23:10

Said Kaldybaev


I think the good solution of your problem is custom renderer. The best approach was described by Jose Valim (!Rails core developer) in his book. The beginning of the first chapter is available for free here. This chapter is really what you need.

like image 40
caulfield Avatar answered Oct 06 '22 01:10

caulfield


This how I do it:

class CustomerPdf< Prawn::Document

 def initialize(customer)
  super(page_size: "A4", page_layout: :portrait)
  @customers = customer
  bullet_list
 end

 def bullet_list
  @customers.each do |customer|
      text "•#{customer.id}- #{customer.name} ", style: :bold
    move_down 5
  end
 end

end
like image 29
Frank004 Avatar answered Oct 05 '22 23:10

Frank004