first version

This commit is contained in:
Loic Nageleisen 2013-10-22 17:41:08 +02:00
commit e2c2846b81
11 changed files with 303 additions and 0 deletions

1
lib/tilt-pdf.rb Normal file
View file

@ -0,0 +1 @@
require 'tilt/pdf'

88
lib/tilt/pdf.rb Normal file
View file

@ -0,0 +1,88 @@
require 'pdfkit'
require 'tilt'
require 'tilt/template'
PDFKit.configure do |config|
config.wkhtmltopdf =
'/Applications/wkhtmltopdf.app/Contents/MacOS/wkhtmltopdf'
config.default_options = {
page_size: 'A4',
orientation: 'portrait',
print_media_type: true,
dpi: 600,
margin_top: 0,
margin_bottom: 0,
margin_left: 0,
margin_right: 0,
header_spacing: 0,
footer_spacing: 0,
disable_smart_shrinking: true,
zoom: 1.0,
}
end
module Tilt
class PDFTemplate < Template
self.default_mime_type = 'application/pdf'
def prepare; end
def evaluate(scope, locals, &block)
html_file = find_html
html = render_html(html_file, scope, locals, &block)
css_files = find_css
render_css(*css_files) do |*css|
kit = PDFKit.new(html, pdfkit_options)
css.each { |f| kit.stylesheets << f }
@output = kit.to_pdf
end
@output
end
private
def pdfkit_options
YAML.load(data) || {}
end
def dirname
eval_file.gsub(/#{basename}$/, '').chomp('/')
end
def find_html
Dir.glob(File.join(dirname, name + '.html*')).first
end
def find_css
Dir.glob(File.join(dirname, name + '.css*'))
end
def render_html(file, scope, locals, &block)
Tilt.new(file).render(scope, locals, &block)
end
def render_css(*files)
tmps = []
files.each do |file|
case file
when /.*\.css$/
yield file
else
tmp = Tempfile.new(File.basename(file))
tmps << tmp
css = Tilt.new(file).render
tmp.write(css)
tmp.close
yield tmp.path
end
end
ensure
tmps.each { |tmp| tmp.close! }
end
end
end
Tilt.register Tilt::PDFTemplate, 'rpdf'

25
lib/tilt/pdf/rails.rb Normal file
View file

@ -0,0 +1,25 @@
require 'tilt-pdf'
require 'action_view/template/handlers'
module ActionView
class Template
module Handlers
class PDFTemplate
class_attribute :default_format
self.default_format = :pdf
def call(template)
"Tilt.new('#{template.identifier}').render(self)"
end
end
end
register_template_handler :rpdf, Handlers::PDFTemplate.new
end
end
module Tilt::PDFTemplate::Rails
class Railtie < ::Rails::Railtie
config.app_generators.template_engine :rpdf
end
end

6
lib/tilt/pdf/version.rb Normal file
View file

@ -0,0 +1,6 @@
module Tilt
module PDF
VERSION = '0.1.0'
end
end