Some days ago, Ruby On Rails 2.1 saw the light of day and as usual, i eagerly updated my Daily Fratze project.
I had some minor problems due to an old version of will_paginate and some major ones with my use of PDF::Writer.
The PDF::Writer library still works very well but the the instructions here (under PDF::Writer (Austin Ziegler) on how the register an “rpdf” template handler don’t apply anymore due to changes in the Rails template system but can easily be fixed:
In environment.rb change
ActionView::Base.register_template_handler 'rpdf', ActionView::PDFRender |
to
ActionView::Template.register_template_handler 'rpdf', ActionView::PDFRender |
And also change your ActionView::PDFRender class to:
module ActionView # :nodoc: require 'pdf/writer' class PDFRender PAPER = 'A4' include ApplicationHelper include ActionView::Helpers::AssetTagHelper include ActionView::Helpers::TextHelper include ActionView::Helpers::TagHelper include ActionView::Helpers::UrlHelper def initialize(action_view) @action_view = action_view end # Render the PDF def render(template, local_assigns = {}) @action_view.controller.headers["Content-Type"] ||= 'application/pdf' # Retrieve controller variables @action_view.controller.instance_variables.each do |v| instance_variable_set(v, @action_view.controller.instance_variable_get(v)) end pdf = ::PDF::Writer.new( :paper => PAPER ) pdf.compressed = true if RAILS_ENV != 'development' eval template.source, nil, "#{@action_view.base_path}/#{@action_view.first_render}.#{@action_view.finder.pick_template_extension(@action_view.first_render)}" pdf.render end def self.compilable? false end def compilable? self.class.compilable? end end end |
And enjoy happy PDF generation 😉
7 comments
Thanks for this post. Where should I put the changes to the ActionView::PDFRender Class?
Hey Hugh,
you’re welcome.
This is the complete PDFRender class.
I have it in a file “PDFRender.rb” in $APP_HOME/lib and include it in environment.rb via “require ‘PDFRender'”
Michael – thanks for this.
Graeme: You’re welcome 🙂
Hi,
Thanks for this post
I am using pdf writer to generate pdf in rails application.
i need how to create or set headers and footers for all pages in pdf
Please guide me.
Thanks
Check out “loose content objects” in http://ruby-pdf.rubyforge.org/.....manual.pdf
Hi Michael,
if you are interested in rendering PDFs out of OpenOffice or LibreOffice templates, please take a look at my side project:
http://template2pdf.com/
Aside from normal text substitution it offers support for images and lists. (And all the nice stuff like header/footer or clean page breaks that such word processors offer.)
The API is currently free for low volume usage. I would be very happy to get some feedback.
Thanks,
Best regards,
Sven
One Trackback/Pingback
[…] here and used the method named PDF::Writer (Austin Ziegler), you we’re out of luck when Rails 2.1 […]
Post a Comment