Advanced Example

suggest change

This is a more advanced example:

class FundsController < ApplicationController

 def index
   @funds = Fund.all_funds(current_user)
 end

 def show
   @fund = Fund.find(params[:id])
   respond_to do |format|
     format.html
     format.pdf do
       pdf = FundsPdf.new(@fund, view_context)
       send_data pdf.render, filename: 
       "fund_#{@fund.created_at.strftime("%d/%m/%Y")}.pdf",
       type: "application/pdf"
     end
   end
 end
end

The line FundsPdf.new(@fund, view_context) creates a FundsPdf, passing the fund and the view context so the PDF can call helper methods. FundsPdf looks like this:

class FundsPdf < Prawn::Document

 def initialize(fund, view)
   super()
   @fund = fund
   @view = view
   upper_half
   lower_half
 end

 def upper_half
   logopath =  "#{Rails.root}/app/assets/images/logo.png"
   image logopath, :width => 197, :height => 91
   move_down 10
   draw_text "Receipt", :at => [220, 575], size: 22
   move_down 80
   text "Hello #{@fund.customer.profile.first_name.capitalize},"
 end

 def thanks_message
   move_down 15
   text "Thank you for your order. Print this receipt as confirmation of your order.",
   :indent_paragraphs => 40, :size => 13
 end
end

This is one way to generate a PDF with Prawn by putting the drawing code in its own class.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents