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.
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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With