Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

initial

  • Loading branch information...
commit c3a93ecb39181f41943004fe6a0dd46406bb8850 1 parent f51b405
Lleïr Borràs Metje authored
20 MIT-LICENSE
View
@@ -0,0 +1,20 @@
+Copyright (c) 2012 Lleir Borras Metje
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
247 README.md 100644 → 100755
View
@@ -1,4 +1,245 @@
-go_static
-=========
+# Wicked PDF
-Render views in rails written in html to an image (png, ...)
+## A PDF generation plugin for Ruby on Rails
+
+Wicked PDF uses the shell utility [wkhtmltopdf](http://code.google.com/p/wkhtmltopdf/) to serve a PDF file to a user from HTML. In other words, rather than dealing with a PDF generation DSL of some sort, you simply write an HTML view as you would normally, then let Wicked take care of the hard stuff.
+
+_Wicked PDF has been verified to work on Ruby 1.8.7 and 1.9.2; Rails 2 and Rails 3_
+
+### Installation
+
+First, be sure to install [wkhtmltopdf](http://code.google.com/p/wkhtmltopdf/).
+Note that versions before 0.9.0 [have problems](http://code.google.com/p/wkhtmltopdf/issues/detail?id=82&q=vodnik) on some machines with reading/writing to streams.
+This plugin relies on streams to communicate with wkhtmltopdf.
+
+More information about [wkhtmltopdf](http://code.google.com/p/wkhtmltopdf/) could be found [here](http://madalgo.au.dk/~jakobt/wkhtmltoxdoc/wkhtmltopdf-0.9.9-doc.html).
+
+Next:
+
+ script/plugin install git://github.com/mileszs/wicked_pdf.git
+ script/generate wicked_pdf
+
+or add this to your Gemfile:
+
+ gem 'wicked_pdf'
+
+### Basic Usage
+
+ class ThingsController < ApplicationController
+ def show
+ respond_to do |format|
+ format.html
+ format.pdf do
+ render :pdf => "file_name"
+ end
+ end
+ end
+ end
+
+### Advanced Usage with all available options
+
+ class ThingsController < ApplicationController
+ def show
+ respond_to do |format|
+ format.html
+ format.pdf do
+ render :pdf => 'file_name',
+ :disposition => 'attachment', # default 'inline'
+ :template => 'things/show.pdf.erb',
+ :layout => 'pdf.html', # use 'pdf.html' for a pdf.html.erb file
+ :wkhtmltopdf => '/usr/local/bin/wkhtmltopdf', # path to binary
+ :show_as_html => params[:debug].present?, # allow debuging based on url param
+ :orientation => 'Landscape', # default Portrait
+ :page_size => 'A4, Letter, ...', # default A4
+ :save_to_file => Rails.root.join('pdfs', "#{filename}.pdf"),
+ :save_only => false, # depends on :save_to_file being set first
+ :proxy => 'TEXT',
+ :basic_auth => false # when true username & password are automatically sent from session
+ :username => 'TEXT',
+ :password => 'TEXT',
+ :cover => 'URL',
+ :dpi => 'dpi',
+ :encoding => 'TEXT',
+ :user_style_sheet => 'URL',
+ :cookie => ['_session_id SESSION_ID'], # could be an array or a single string in a 'name value' format
+ :post => ['query QUERY_PARAM'], # could be an array or a single string in a 'name value' format
+ :redirect_delay => NUMBER,
+ :zoom => FLOAT,
+ :page_offset => NUMBER,
+ :book => true,
+ :default_header => true,
+ :disable_javascript => false,
+ :grayscale => true,
+ :lowquality => true,
+ :enable_plugins => true,
+ :disable_internal_links => true,
+ :disable_external_links => true,
+ :print_media_type => true,
+ :disable_smart_shrinking => true,
+ :use_xserver => true,
+ :no_background => true,
+ :extra => '' # directly inserted into the command to wkhtmltopdf
+ :margin => {:top => SIZE, # default 10 (mm)
+ :bottom => SIZE,
+ :left => SIZE,
+ :right => SIZE},
+ :header => {:html => { :template => 'users/header.pdf.erb', # use :template OR :url
+ :layout => 'pdf_plain.html', # optional, use 'pdf_plain.html' for a pdf_plain.html.erb file, defaults to main layout
+ :url => 'www.example.com',
+ :locals => { :foo => @bar }},
+ :center => 'TEXT',
+ :font_name => 'NAME',
+ :font_size => SIZE,
+ :left => 'TEXT',
+ :right => 'TEXT',
+ :spacing => REAL,
+ :line => true,
+ :content => 'HTML CONTENT ALREADY RENDERED'}, # optionally you can pass plain html already rendered (useful if using pdf_from_string)
+ :footer => {:html => { :template => 'shared/footer.pdf.erb', # use :template OR :url
+ :layout => 'pdf_plain.html', # optional, use 'pdf_plain.html' for a pdf_plain.html.erb file, defaults to main layout
+ :url => 'www.example.com',
+ :locals => { :foo => @bar }},
+ :center => 'TEXT',
+ :font_name => 'NAME',
+ :font_size => SIZE,
+ :left => 'TEXT',
+ :right => 'TEXT',
+ :spacing => REAL,
+ :line => true,
+ :content => 'HTML CONTENT ALREADY RENDERED'}, # optionally you can pass plain html already rendered (useful if using pdf_from_string)
+ :toc => {:font_name => "NAME",
+ :depth => LEVEL,
+ :header_text => "TEXT",
+ :header_fs => SIZE,
+ :l1_font_size => SIZE,
+ :l2_font_size => SIZE,
+ :l3_font_size => SIZE,
+ :l4_font_size => SIZE,
+ :l5_font_size => SIZE,
+ :l6_font_size => SIZE,
+ :l7_font_size => SIZE,
+ :l1_indentation => NUM,
+ :l2_indentation => NUM,
+ :l3_indentation => NUM,
+ :l4_indentation => NUM,
+ :l5_indentation => NUM,
+ :l6_indentation => NUM,
+ :l7_indentation => NUM,
+ :no_dots => true,
+ :disable_links => true,
+ :disable_back_links => true},
+ :outline => {:outline => true,
+ :outline_depth => LEVEL}
+ end
+ end
+ end
+ end
+
+By default, it will render without a layout (:layout => false) and the template for the current controller and action.
+
+### Super Advanced Usage ###
+
+If you need to just create a pdf and not display it:
+
+ # create a pdf from a string
+ pdf = WickedPdf.new.pdf_from_string('<h1>Hello There!</h1>')
+
+ # create a pdf from string using templates, layouts and content option for header or footer
+ WickedPdf.new.pdf_from_string(
+ render_to_string(:pdf => "pdf_file.pdf", :template => 'templates/pdf.html.erb', :layout => 'pdfs/layout_pdf'),
+ :footer => {:content => render_to_string({:template => 'templates/pdf_footer.html.erb', :layout => 'pdfs/layout_pdf'})}
+
+ # or from your controller, using views & templates and all wicked_pdf options as normal
+ pdf = render_to_string :pdf => "some_file_name"
+
+ # then save to a file
+ save_path = Rails.root.join('pdfs','filename.pdf')
+ File.open(save_path, 'wb') do |file|
+ file << pdf
+ end
+
+If you need to display utf encoded characters, add this to your pdf views or layouts:
+
+ <meta http-equiv="content-type" content="text/html; charset=utf-8" />
+
+### Styles
+
+You must define absolute paths to CSS files, images, and javascripts; the best option is to use the *wicked_pdf_stylesheet_link_tag*, *wicked_pdf_image_tag*, and *wicked_pdf_javascript_include_tag* helpers.
+
+ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+ <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
+ <head>
+ <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+ <%= wicked_pdf_stylesheet_link_tag "pdf" -%>
+ <%= wicked_pdf_javascript_include_tag "number_pages" %>
+ </head>
+ <body onload='number_pages'>
+ <div id="header">
+ <%= wicked_pdf_image_tag 'mysite.jpg' %>
+ </div>
+ <div id="content">
+ <%= yield %>
+ </div>
+ </body>
+ </html>
+
+### Page Numbering
+
+A bit of javascript can help you number your pages. Create a template or header/footer file with this:
+
+ <html>
+ <head>
+ <script>
+ function number_pages() {
+ var vars={};
+ var x=document.location.search.substring(1).split('&');
+ for(var i in x) {var z=x[i].split('=',2);vars[z[0]] = unescape(z[1]);}
+ var x=['frompage','topage','page','webpage','section','subsection','subsubsection'];
+ for(var i in x) {
+ var y = document.getElementsByClassName(x[i]);
+ for(var j=0; j<y.length; ++j) y[j].textContent = vars[x[i]];
+ }
+ }
+ </script>
+ </head>
+ <body onload="number_pages()">
+ Page <span class="page"></span> of <span class="topage"></span>
+ </body>
+ </html>
+
+Anything with a class listed in "var x" above will be auto-filled at render time.
+
+If you do not have explicit page breaks (and therefore do not have any "page" class), you can also use wkhtmltopdf's built in page number generation by setting one of the headers to "[page]":
+
+ render :pdf => 'filename', :header => { :right => '[page] of [topage]' }
+
+### Configuration
+
+You can put your default configuration, applied to all pdf's at "wicked_pdf.rb" initializer.
+
+### Further Reading
+
+Andreas Happe's post [Generating PDFs from Ruby on Rails](http://snikt.net/rails/2012/04/26/wicked-pdf/)
+
+StackOverflow [questions with the tag "wicked-pdf"](http://stackoverflow.com/questions/tagged/wicked-pdf)
+
+### Debugging
+
+Now you can use a debug param on the URL that shows you the content of the pdf in plain html to design it faster.
+
+First of all you must configure the render parameter ":show_as_html => params[:debug]" and then just use it like normally but adding "debug=1" as a param:
+
+http://localhost:3001/CONTROLLER/X.pdf?debug=1
+
+However, the wicked_pdf_* helpers will use file:// paths for assets when using :show_as_html, and your browser's cross-domain safety feature will kick in, and not render them. To get around this, you can load your assets like so in your templates:
+
+ <%= params[:debug].present? ? image_tag('foo') : wicked_pdf_image_tag('foo') %>
+
+### Inspiration
+
+You may have noticed: this plugin is heavily inspired by the PrinceXML plugin [princely](http://github.com/mbleigh/princely/tree/master). PrinceXML's cost was prohibitive for me. So, with a little help from some friends (thanks [jqr](http://github.com/jqr)), I tracked down wkhtmltopdf, and here we are.
+
+### Awesome Peoples
+
+Also, thanks to [unixmonkey](https://github.com/Unixmonkey), [galdomedia](http://github.com/galdomedia), [jcrisp](http://github.com/jcrisp), [lleirborras](http://github.com/lleirborras), [tiennou](http://github.com/tiennou), and everyone else for all their hard work and patience with my delays in merging in their enhancements.
23 Rakefile
View
@@ -0,0 +1,23 @@
+require 'rake'
+require 'rake/testtask'
+require 'rake/rdoctask'
+
+desc 'Default: run unit tests.'
+task :default => :test
+
+desc 'Test the go_static plugin.'
+Rake::TestTask.new(:test) do |t|
+ t.libs << 'lib'
+ t.libs << 'test'
+ t.pattern = 'test/**/*_test.rb'
+ t.verbose = true
+end
+
+desc 'Generate documentation for the go_static plugin.'
+Rake::RDocTask.new(:rdoc) do |rdoc|
+ rdoc.rdoc_dir = 'rdoc'
+ rdoc.title = 'GoStatic'
+ rdoc.options << '--line-numbers' << '--inline-source'
+ rdoc.rdoc_files.include('README')
+ rdoc.rdoc_files.include('lib/**/*.rb')
+end
4 VERSION.yml
View
@@ -0,0 +1,4 @@
+---
+:patch: 0
+:minor: 1
+:major: 0
7 generators/go_static/go_static_generator.rb
View
@@ -0,0 +1,7 @@
+class GoStaticGenerator < Rails::Generator::Base
+ def manifest
+ record do |m|
+ m.file "go_static.rb", "config/initializers/go_static.rb"
+ end
+ end
+end
4 generators/go_static/templates/go_static.rb
View
@@ -0,0 +1,4 @@
+GoStatic.config = {
+ #:wkhtmltoimage => '/usr/local/bin/wkhtmltoimage',
+ :exe_path => '/usr/local/bin/wkhtmltoimage'
+}
18 go_static.gemspec
View
@@ -0,0 +1,18 @@
+Gem::Specification.new do |s|
+ s.name = "go_static"
+ s.version = "0.0.1"
+ s.date = Time.now.strftime('%Y-%m-%d')
+ s.summary = "Render views in Ruby on Rails written in html to an image (png, ...)"
+ s.homepage = "http://github.com/lleirborras/go_static"
+ s.email = "lleir@llegeix.me"
+ s.authors = [ "Lleir Borras Metje" ]
+
+ s.files = %w( README.md Rakefile MIT-LICENSE )
+ s.files += Dir.glob("lib/**/*")
+ s.files += Dir.glob("test/**/*")
+
+ s.description = <<desc
+GoStatic uses the shell utility wkhtmltoimage to serve an image file to a user from HTML.
+You simply write an HTML view as you would normally, and let GoStatic take care of the hard stuff.
+desc
+end
12 init.rb
View
@@ -0,0 +1,12 @@
+require 'go_static'
+require 'go_static_tempfile'
+
+unless ActionController::Base.instance_methods.collect(&:to_s).include? "render_with_go_static"
+ require 'static_helper'
+ ActionController::Base.send :include, StaticHelper
+end
+
+unless ActionView::Base.instance_methods.collect(&:to_s).include? "go_static_stylesheet_link_tag"
+ require 'go_static_helper'
+ ActionView::Base.send :include, GoStaticHelper
+end
11 lib/generators/go_static_generator.rb
View
@@ -0,0 +1,11 @@
+if defined?(Rails) && Rails::VERSION::MAJOR != 2
+
+ # Rails3 generator invoked with 'rails generate go_static'
+ class GoStaticGenerator < Rails::Generators::Base
+ source_root(File.expand_path(File.dirname(__FILE__) + "/../../generators/go_static/templates"))
+ def copy_initializer
+ copy_file 'go_static.rb', 'config/initializers/go_static.rb'
+ end
+ end
+
+end
165 lib/go_static.rb
View
@@ -0,0 +1,165 @@
+# wkhtml2image Ruby interface
+# http://code.google.com/p/wkhtmltopdf/
+
+require 'logger'
+require 'digest/md5'
+require 'rbconfig'
+require RbConfig::CONFIG['target_os'] == 'mingw32' && !(RUBY_VERSION =~ /1.9/) ? 'win32/open3' : 'open3'
+require 'active_support/core_ext/class/attribute_accessors'
+require 'active_support/core_ext/object/blank'
+
+require 'go_static_railtie'
+require 'go_static_tempfile'
+
+class GoStatic
+ EXE_NAME = "wkhtmltoimage"
+ @@config = {}
+ cattr_accessor :config
+
+ def initialize(wkhtmltoimage_binary_path = nil)
+ @exe_path = wkhtmltoimage_binary_path || find_wkhtmltoimage_binary_path
+ raise "Location of #{EXE_NAME} unknown" if @exe_path.empty?
+ raise "Bad #{EXE_NAME}'s path" unless File.exists?(@exe_path)
+ raise "#{EXE_NAME} is not executable" unless File.executable?(@exe_path)
+ end
+
+ def png_from_string(string, options={})
+ command = "\"#{@exe_path}\" #{parse_options(options)} - - " # -q for no errors on stdout
+ print_command(command) if in_development_mode?
+ png, err = Open3.popen3(command) do |stdin, stdout, stderr|
+ stdin.binmode
+ stdout.binmode
+ stderr.binmode
+ stdin.write(string)
+ stdin.close
+ [stdout.read, stderr.read]
+ end
+ raise "IMAGE could not be generated!" if png and png.rstrip.length == 0
+ png
+ rescue Exception => e
+ raise "Failed to execute:\n#{command}\nError: #{e}"
+ end
+
+ private
+
+ def in_development_mode?
+ (defined?(Rails) && Rails.env == 'development') ||
+ (defined?(RAILS_ENV) && RAILS_ENV == 'development')
+ end
+
+ def on_windows?
+ RbConfig::CONFIG['target_os'] == 'mingw32'
+ end
+
+ def print_command(cmd)
+ p "*"*15 + cmd + "*"*15
+ end
+
+ def parse_options(options)
+ [
+ parse_extra(options),
+ parse_basic_auth(options),
+ parse_others(options)
+ ].join(' ')
+ end
+
+ def parse_extra(options)
+ options[:extra].nil? ? '' : options[:extra]
+ end
+
+ def parse_basic_auth(options)
+ if options[:basic_auth]
+ user, passwd = Base64.decode64(options[:basic_auth]).split(":")
+ "--username '#{user}' --password '#{passwd}'"
+ else
+ ""
+ end
+ end
+
+ def make_option(name, value, type=:string)
+ if value.is_a?(Array)
+ return value.collect { |v| make_option(name, v, type) }.join('')
+ end
+ "--#{name.gsub('_', '-')} " + case type
+ when :boolean then ""
+ when :numeric then value.to_s
+ when :name_value then value.to_s
+ else "\"#{value}\""
+ end + " "
+ end
+
+ def make_options(options, names, prefix="", type=:string)
+ names.collect {|o| make_option("#{prefix.blank? ? "" : prefix + "-"}#{o.to_s}", options[o], type) unless options[o].blank?}.join
+ end
+
+ def parse_others(options)
+ unless options.blank?
+ r = make_options(options, [ :cookie,
+ :custom_header,
+ :post,
+ :post_file], "", :name_value)
+
+ r +=make_options(options, [ :crop_h,
+ :crop_w,
+ :crop_x,
+ :crop_y,
+ :minimum_font_size,
+ :quality,
+ :width,
+ :zoom], "", :numeric)
+
+ r +=make_options(options, [ :custom_header_propagation,
+ :no_custom_header_propagation,
+ :debug_javascript,
+ :no_debug_javascript,
+ :help,
+ :htmldoc,
+ :images,
+ :no_images,
+ :disable_javascript,
+ :enable_javascript,
+ :disable_local_file_access,
+ :enable_local_file_access,
+ :manpage,
+ :disable_plugins,
+ :enable_plugins,
+ :readme,
+ :disable_smart_width,
+ :stop_slow_scripts,
+ :no_stop_slow_scripts,
+ :transparent,
+ :version,
+ :extended_help])
+
+ r +=make_options(options, [ :allow,
+ :checkbox_checked_svg,
+ :checkbox_svg,
+ :cookie_jar,
+ :encoding,
+ :format,
+ :height,
+ :javascript_delay,
+ :load_error_handling,
+ :password,
+ :proxy,
+ :radiobutton_checked_svg,
+ :radiobutton_svg,
+ :run_script,
+ :user_style_sheet,
+ :username,
+ :window_status])
+ end
+ end
+
+ def find_wkhtmltoimage_binary_path
+ possible_locations = (ENV['PATH'].split(':')+%w[/usr/bin /usr/local/bin ~/bin]).uniq
+ exe_path ||= GoStatic.config[:exe_path] unless GoStatic.config.empty?
+ exe_path ||= begin
+ (defined?(Bundler) ? `bundle exec which wkhtmltoimage` : `which wkhtmltoimage`).chomp
+ rescue Exception => e
+ nil
+ end
+ exe_path ||= possible_locations.map{|l| File.expand_path("#{l}/#{EXE_NAME}") }.find{|location| File.exists? location}
+ exe_path || ''
+ end
+end
60 lib/go_static_helper.rb
View
@@ -0,0 +1,60 @@
+module GoStaticHelper
+ def go_static_stylesheet_link_tag(*sources)
+ css_dir = Rails.root.join('public','stylesheets')
+ sources.collect { |source|
+ "<style type='text/css'>#{File.read(css_dir.join(source+'.css'))}</style>"
+ }.join("\n").html_safe
+ end
+
+ def go_static_image_tag(img, options={})
+ image_tag "file:///#{Rails.root.join('public', 'images', img)}", options
+ end
+
+ def go_static_javascript_src_tag(jsfile, options={})
+ javascript_src_tag "file:///#{Rails.root.join('public','javascripts',jsfile)}", options
+ end
+
+ def go_static_javascript_include_tag(*sources)
+ sources.collect{ |source| go_static_javascript_src_tag(source, {}) }.join("\n").html_safe
+ end
+
+ module Assets
+ def go_static_stylesheet_link_tag(*sources)
+ sources.collect { |source|
+ "<style type='text/css'>#{read_asset(source+".css")}</style>"
+ }.join("\n").html_safe
+ end
+
+ def go_static_image_tag(img, options={})
+ image_tag "file://#{asset_pathname(img).to_s}", options
+ end
+
+ def go_static_javascript_src_tag(jsfile, options={})
+ javascript_include_tag "file://#{asset_pathname(jsfile).to_s}", options
+ end
+
+ def go_static_javascript_include_tag(*sources)
+ sources.collect { |source|
+ "<script type='text/javascript'>#{read_asset(source+".js")}</script>"
+ }.join("\n").html_safe
+ end
+
+ private
+
+ def asset_pathname(source)
+ if Rails.configuration.assets.compile == false
+ File.join(Rails.public_path, asset_path(source))
+ else
+ Rails.application.assets.find_asset(source).pathname
+ end
+ end
+
+ def read_asset(source)
+ if Rails.configuration.assets.compile == false
+ IO.read(asset_pathname(source))
+ else
+ Rails.application.assets.find_asset(source).to_s
+ end
+ end
+ end
+end
30 lib/go_static_railtie.rb
View
@@ -0,0 +1,30 @@
+require 'static_helper'
+require 'go_static_helper'
+
+if defined?(Rails)
+
+ if Rails::VERSION::MAJOR == 2
+
+ unless ActionController::Base.instance_methods.include? "render_with_go_static"
+ ActionController::Base.send :include, StaticHelper
+ end
+ unless ActionView::Base.instance_methods.include? "go_static_stylesheet_link_tag"
+ ActionView::Base.send :include, GoStaticHelper
+ end
+
+ else
+
+ class StaticRailtie < Rails::Railtie
+ initializer "go_static.register" do |app|
+ ActionController::Base.send :include, StaticHelper
+ if Rails::VERSION::MINOR > 0
+ ActionView::Base.send :include, GoStaticHelper::Assets
+ else
+ ActionView::Base.send :include, GoStaticHelper
+ end
+ end
+ end
+
+ end
+
+end
10 lib/go_static_tempfile.rb
View
@@ -0,0 +1,10 @@
+require 'tempfile'
+
+class GoStaticTempfile < Tempfile
+ # Replaces Tempfile's +make_tmpname+ with one that honors file extensions.
+ def make_tmpname(basename, n)
+ extension = File.extname(basename)
+ sprintf("%s_%d_%d%s", File.basename(basename, extension), $$, n.to_i, extension)
+ end
+end
+
72 lib/static_helper.rb
View
@@ -0,0 +1,72 @@
+module StaticHelper
+ require 'go_static'
+ require 'go_static_tempfile'
+
+ def self.included(base)
+ base.class_eval do
+ alias_method_chain :render, :go_static
+ alias_method_chain :render_to_string, :go_static
+ after_filter :clean_temp_files
+ end
+ end
+
+ def render_with_go_static(options = nil, *args, &block)
+ if options.is_a?(Hash) && options.has_key?(:png)
+ log_png_creation
+ options[:basic_auth] = set_basic_auth(options)
+ make_and_send_png(options.delete(:png), (GoStatic.config || {}).merge(options))
+ else
+ render_without_go_static(options, *args, &block)
+ end
+ end
+
+ def render_to_string_with_go_static(options = nil, *args, &block)
+ if options.is_a?(Hash) && options.has_key?(:png)
+ log_png_creation
+ options[:basic_auth] = set_basic_auth(options)
+ options.delete :png
+ make_png((GoStatic.config || {}).merge(options))
+ else
+ render_to_string_without_go_static(options, *args, &block)
+ end
+ end
+
+ private
+
+ def log_png_creation
+ logger.info '*'*15 + 'STATIC' + '*'*15
+ end
+
+ def set_basic_auth(options={})
+ options[:basic_auth] ||= GoStatic.config.fetch(:basic_auth){ false }
+ if options[:basic_auth] && request.env["HTTP_AUTHORIZATION"]
+ request.env["HTTP_AUTHORIZATION"].split(" ").last
+ end
+ end
+
+ def clean_temp_files
+ if defined?(@hf_tempfiles)
+ @hf_tempfiles.each { |tf| tf.close! }
+ end
+ end
+
+ def make_png(options = {})
+ html_string = render_to_string(:template => options[:template], :layout => options[:layout], :formats => options[:formats], :handlers => options[:handlers])
+ w = GoStatic.new(options[:wkhtmltoimage])
+ w.png_from_string(html_string)
+ end
+
+ def make_and_send_png(png_name, options={})
+ options[:wkhtmltoimage] ||= nil
+ options[:layout] ||= false
+ options[:template] ||= File.join(controller_path, action_name)
+ options[:disposition] ||= "inline"
+ if options[:show_as_html]
+ render :template => options[:template], :layout => options[:layout], :formats => options[:formats], :handlers => options[:handlers], :content_type => "text/html"
+ else
+ png_content = make_png(options)
+ File.open(options[:save_to_file], 'wb') {|file| file << png_content } if options[:save_to_file]
+ send_data(png_content, :filename => png_name + '.png', :type => 'application/png', :disposition => options[:disposition]) unless options[:save_only]
+ end
+ end
+end
1  test/fixtures/static.css
View
@@ -0,0 +1 @@
+/* Wicked styles */
24 test/go_static_helper_test.rb
View
@@ -0,0 +1,24 @@
+require 'test_helper'
+require 'action_view/test_case'
+
+class GoStaticHelperTest < ActionView::TestCase
+ test 'go_static_stylesheet_link_tag should inline the stylesheets passed in' do
+ assert_equal "<style type='text/css'>/* Wicked styles */\n</style>",
+ go_static_stylesheet_link_tag('../../vendor/plugins/go_static/test/fixtures/wicked')
+ end
+
+ test 'go_static_image_tag should return the same as image_tag when passed a full path' do
+ assert_equal image_tag("file://#{Rails.root.join('public','images','png')}"),
+ go_static_image_tag('png')
+ end
+
+ test 'go_static_javascript_src_tag should return the same as javascript_src_tag when passed a full path' do
+ assert_equal javascript_src_tag("file://#{Rails.root.join('public','javascripts','png')}", {}),
+ go_static_javascript_src_tag('png')
+ end
+
+ test 'go_static_include_tag should return many go_static_javascript_src_tags' do
+ assert_equal [go_static_javascript_src_tag('foo'), go_static_javascript_src_tag('bar')].join("\n"),
+ go_static_javascript_include_tag('foo', 'bar')
+ end
+end
82 test/go_static_test.rb
View
@@ -0,0 +1,82 @@
+require 'test_helper'
+
+GoStatic.config = { :exe_path => '/usr/local/bin/wkhtmltoimage' }
+HTML_DOCUMENT = "<html><body>Hello World</body></html>"
+
+# Provide a public accessor to the normally-private parse_options function
+class GoStatic
+ def get_parsed_options(opts)
+ parse_options(opts)
+ end
+end
+
+class GoStaticTest < ActiveSupport::TestCase
+
+ test "should generate PDF from html document" do
+ wp = GoStatic.new
+ png = wp.png_from_string HTML_DOCUMENT
+ assert png.length > 100
+ end
+
+ test "should raise exception when no path to wkhtmltopng" do
+ assert_raise RuntimeError do
+ GoStatic.new " "
+ end
+ end
+
+ test "should raise exception when wkhtmltopng path is wrong" do
+ assert_raise RuntimeError do
+ GoStatic.new "/i/do/not/exist/notwkhtmltopng"
+ end
+ end
+
+ test "should raise exception when wkhtmltopng is not executable" do
+ begin
+ tmp = Tempfile.new('wkhtmltopng')
+ fp = tmp.path
+ File.chmod 0000, fp
+ assert_raise RuntimeError do
+ GoStatic.new fp
+ end
+ ensure
+ tmp.delete
+ end
+ end
+
+ test "should raise exception when png generation fails" do
+ begin
+ tmp = Tempfile.new('wkhtmltopng')
+ fp = tmp.path
+ File.chmod 0777, fp
+ wp = GoStatic.new fp
+ assert_raise RuntimeError do
+ wp.png_from_string HTML_DOCUMENT
+ end
+ ensure
+ tmp.delete
+ end
+ end
+
+ test "should parse other options" do
+ wp = GoStatic.new
+
+=begin
+ [ :orientation, :page_size, :proxy, :username, :password, :cover, :dpi,
+ :encoding, :user_style_sheet
+ ].each do |o|
+ assert_equal "--#{o.to_s.gsub('_', '-')} \"opts\"", wp.get_parsed_options(o => "opts").strip
+ end
+
+ [:redirect_delay, :zoom, :page_offset].each do |o|
+ assert_equal "--#{o.to_s.gsub('_', '-')} 5", wp.get_parsed_options(o => 5).strip
+ end
+
+ [ :book, :default_header, :disable_javascript, :grayscale, :lowquality,
+ :enable_plugins, :disable_internal_links, :disable_external_links,
+ :print_media_type, :disable_smart_shrinking, :use_xserver, :no_background
+ ].each do |o|
+ assert_equal "--#{o.to_s.gsub('_', '-')}", wp.get_parsed_options(o => true).strip
+ end
+=end
+ end
+end
19 test/static_helper_test.rb
View
@@ -0,0 +1,19 @@
+require 'test_helper'
+
+module ActionController
+ class Base
+ def render_to_string opts={}
+ opts.to_s
+ end
+ end
+end
+
+class StaticHelperTest < ActionController::TestCase
+ def setup
+ @ac = ActionController::Base.new
+ end
+
+ def teardown
+ @ac=nil
+ end
+end
5 test/test_helper.rb
View
@@ -0,0 +1,5 @@
+require 'rubygems'
+require 'test/unit'
+require 'rails'
+require 'action_controller/test_case'
+require 'go_static'
Please sign in to comment.
Something went wrong with that request. Please try again.