Class: WickedPdf

Inherits:
Object
  • Object
show all
Defined in:
lib/wicked_pdf.rb,
lib/wicked_pdf/version.rb,
lib/wicked_pdf/middleware.rb

Defined Under Namespace

Classes: Middleware

Constant Summary collapse

DEFAULT_BINARY_VERSION =
Gem::Version.new('0.9.9')
BINARY_VERSION_WITHOUT_DASHES =
Gem::Version.new('0.12.0')
EXE_NAME =
'wkhtmltopdf'
VERSION =
'0.11.0'
@@config =
{}

Instance Method Summary collapse

Constructor Details

#initialize(wkhtmltopdf_binary_path = nil) ⇒ WickedPdf

Returns a new instance of WickedPdf


38
39
40
41
42
43
44
45
# File 'lib/wicked_pdf.rb', line 38

def initialize(wkhtmltopdf_binary_path = nil)
  @exe_path = wkhtmltopdf_binary_path || find_wkhtmltopdf_binary_path
  fail "Location of #{EXE_NAME} unknown" if @exe_path.empty?
  fail "Bad #{EXE_NAME}'s path: #{@exe_path}" unless File.exist?(@exe_path)
  fail "#{EXE_NAME} is not executable" unless File.executable?(@exe_path)

  retreive_binary_version
end

Instance Method Details

#pdf_from_html_file(filepath, options = {}) ⇒ Object


47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/wicked_pdf.rb', line 47

def pdf_from_html_file(filepath, options = {})
  # merge in global config options
  options.merge!(WickedPdf.config) {|key, option, config| option}
  generated_pdf_file = WickedPdfTempfile.new("wicked_pdf_generated_file.pdf", options[:temp_path])
  command = [@exe_path]
  command << '-q' unless on_windows? # suppress errors on stdout
  command += parse_options(options)
  command << "file:///#{filepath}"
  command << generated_pdf_file.path.to_s

  print_command(command.inspect) if in_development_mode?

  err = Open3.popen3(*command) do |stdin, stdout, stderr|
    stderr.read
  end
  if return_file = options.delete(:return_file)
    return generated_pdf_file
  end
  generated_pdf_file.rewind
  generated_pdf_file.binmode
  pdf = generated_pdf_file.read
  fail "PDF could not be generated!\n Command Error: #{err}" if pdf && pdf.rstrip.length == 0
  pdf
rescue => e
  raise "Failed to execute:\n#{command}\nError: #{e}"
ensure
  generated_pdf_file.close! if generated_pdf_file && !return_file
end

#pdf_from_string(string, options = {}) ⇒ Object


76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/wicked_pdf.rb', line 76

def pdf_from_string(string, options = {})
  # merge in global config options
  options.merge!(WickedPdf.config) {|key, option, config| option}
  string_file = WickedPdfTempfile.new("wicked_pdf.html", options[:temp_path])
  string_file.binmode
  string_file.write(string)
  string_file.close

  pdf = pdf_from_html_file(string_file.path, options)
  pdf
rescue => e
  raise "Error: #{e}"
ensure
  string_file.close! if string_file
end