Created
June 22, 2012 03:12
-
-
Save alakra/2969961 to your computer and use it in GitHub Desktop.
PDF Generation from Ruby (using wkhtmltopdf)
This file contains 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
class PDF | |
PATH = "#{Rails.root}/pdfs" | |
TMP_PATH = "#{Rails.root}/tmp/pdfs" | |
DEFAULT_OPTIONS = { | |
'footer-center' => 'Page [page]', | |
'footer-left' => "Mealr.net", | |
'footer-right' => "Copyright #{Time.now.strftime('%Y')}", | |
'margin-top' => '0.75in', | |
'margin-bottom' => '0.5in', | |
'margin-right' => '0.5in', | |
'margin-left' => '0.5in', | |
'page-size' => 'Letter', | |
'header-spacing' => '5', | |
'encoding' => 'UTF-8' | |
#'load-error-handling' => 'ignore' # @todo, upgrade wkhtmltopdf on mealr server | |
} | |
EXECUTABLE = '/usr/bin/env wkhtmltopdf' | |
attr_accessor :options, :source, :filename, :header, :stylesheets, :xmlpath, :pdfpath, :headerpath | |
def initialize(id, source, filename = nil, options = {}) | |
@options = DEFAULT_OPTIONS | |
@options.merge options | |
@source = source | |
@id = id | |
@filename = filename ? filename : @id | |
@xmlpath = "#{TMP_PATH}/#{@id}.xml" | |
@headerpath = "#{TMP_PATH}/#{@id}-header.xml" | |
@pdfpath = "#{PATH}/#{@filename}.pdf" | |
create_pdf_dir | |
end | |
def to_pdf | |
add_stylesheets | |
check_for_custom_header | |
save_source_as_xml | |
generate_pdf | |
end | |
protected | |
def create_pdf_dir | |
Dir.mkdir("#{PATH}") unless Dir.exists?("#{PATH}") | |
Dir.mkdir("#{TMP_PATH}") unless Dir.exists?("#{TMP_PATH}") | |
end | |
def save_source_as_xml | |
f = File.new(@xmlpath, "w") | |
f.write @source | |
f.close | |
end | |
def add_stylesheets | |
if @stylesheets.is_a? Array | |
@stylesheets.each do |stylesheet| | |
add_stylesheet stylesheet | |
end | |
elsif @stylesheets.is_a? String | |
add_stylesheet stylesheet | |
end | |
end | |
def add_stylesheet(path) | |
@source = @source.gsub(/(<\/head>)/, "<style>#{File.read(path)}</style>" +'\1') | |
end | |
def check_for_custom_header | |
f = File.new(@headerpath, "w") | |
f.write @header | |
f.close | |
@options['header-html'] = @headerpath | |
end | |
def generate_pdf | |
options = @options.map {|k,v| "--#{k} \"#{v}\"" } | |
command = "#{EXECUTABLE} #{options.join(' ')} --quiet #{@xmlpath} #{@pdfpath}" | |
system(command) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment