Figuring out how to generate a PDF using prawn and prawnto has been easy in some respects and difficult in others, but I finally figured out how to get create a PDF and upload it to scribd as well as generate the pdf to just display to the user.
In the prawnto plugin, I changed the render method so it looks like this:
def render(template)
pull_prawnto_options
build_headers
source = build_source_to_establish_locals(template)
if @prawnto_options[:dsl] || @prawnto_options[:dsl_pdf]
source += "pdf.instance_eval do\n#{template.source}\nend"
else
source += "\n#{template.source}"
end
pdf = Prawn::Document.new(@prawnto_options[:prawn])
if @prawnto_options[:dsl_pdf]
@prawnto_options[:dsl_pdf].each { |key,value|
pdf.instance_variable_set( "#{key}", value)
}
end
@view.instance_eval source, template.filename, 1
pdf.render
end
Basically I added another option called dsl_pdf. I suppose there may be a better way of doing it, but this works for now.
Then in my controller I can have this:
def print_work_orders
@units = Unit.find(:all)
@stages = Stage.find(:all)
respond_to do |format|
format.html {
Scribd::API.instance.key = '**********************'
Scribd::API.instance.secret = '**************************'
user = Scribd::User.login '**********', '*********'
source_filename = "#{RAILS_ROOT}/app/views/housing/construction/print_work_orders.pdf.prawn"
resulting_filename = "#{RAILS_ROOT}/public/files/chumba.pdf"
generate_report(source_filename, resulting_filename, {:units => @units, :stages => @stages})
@doc = Scribd::Document.upload(:file => resulting_filename, :access => 'private')
while !@doc.created? do end
@doc.tags = "globaltrack,\"construction work order\",#{RAILS_ENV}"
@doc.save
}
format.pdf {
prawnto :dsl_pdf=> {'@units' => @units, '@stages' => @stages}, :inline => false
render :layout => false
}
end
end
And finally, in the application controller I have the following:
def generate_report(filename, resulting_filename, options = {})
source_file = File::open(filename);
source = source_file.read
Prawn::Document.generate(resulting_filename) do |pdf|
options.each { |key,value|
pdf.instance_variable_set( "@#{key}", value)
}
pdf.instance_eval(source, filename, 1)
end
end
The real magic is in the fact that the instance variables passed through the dsl_pdf option are then added to the pdf document object, thus enabling them to be used in the template and it doesn’t matter if it’s being rendered return content to the browser or if it’s being generated as a file and then uploaded to scribd.
0 Responses
Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.