Created
January 28, 2009 11:36
-
-
Save vjt/53906 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# Action View hook for .rpdf views, to have them filtered via htmldoc and | |
# rendered as a PDF file. | |
# | |
# Put it in your lib/ directory, save it with a name of your choice, and require | |
# it in your environment.rb. Sample controller usage is below. | |
# | |
# Your view must be an HTML 3.2 file, and you can use the additional HTMLDOC comments. | |
# | |
# See <http://www.htmldoc.org/> for more information oh htmldoc, and | |
# <http://htmldoc.rubyforge.org/> for more information on the htmldoc gem. | |
# | |
# In your controller, do something equivalent (default REST routes assumed): | |
# | |
# class YourController < ApplicationController | |
# def some_action | |
# format = params[:format] || 'html' | |
# render :action => "show.r#{format}", :content_type => Mime.const_get(format.upcase) | |
# end | |
# end | |
# | |
# Untested with Rails versions 2.1 and upwards. Feedback is welcome :). | |
# | |
# - [email protected] | |
require 'htmldoc' | |
class PDF::HTMLDoc::View | |
include ApplicationHelper | |
include ActionView::Helpers::TagHelper | |
include ActionView::Helpers::UrlHelper | |
def initialize(action_view) | |
@action_view = action_view | |
@controller = @action_view.controller | |
end | |
# Render the PDF | |
def render(template, local_assigns = {}) | |
@controller.headers['Content-Disposition'] ||= 'attachment' | |
@controller.instance_variables.each do |v| | |
instance_variable_set(v, @controller.instance_variable_get(v)) | |
end | |
markup = ERB.new(template).result(binding) | |
PDF::HTMLDoc.create do |pdf| | |
{ :bodycolor => :white, :toc => false, :portrait => true, | |
:links => true, :webpage => true, :left => '2cm', :right => '2cm', | |
:path => (Pathname.new(File.join(RAILS_ROOT, 'public')).realpath.to_s) | |
}.each do |option, value| pdf.set_option option, value end | |
pdf << markup | |
end | |
end | |
end | |
ActionView::Base.register_template_handler 'rpdf', PDF::HTMLDoc::View | |
Mime::Type.register 'application/pdf', :pdf | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment