Class: WickedPdf

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

Defined Under Namespace

Classes: Middleware

Constant Summary collapse

EXE_NAME =
"wkhtmltopdf"
@@config =
{}

Instance Method Summary collapse

Constructor Details

#initialize(wkhtmltopdf_binary_path = nil) ⇒ WickedPdf

Returns a new instance of WickedPdf


25
26
27
28
29
30
# File 'lib/wicked_pdf.rb', line 25

def initialize(wkhtmltopdf_binary_path = nil)
  @exe_path = wkhtmltopdf_binary_path || find_wkhtmltopdf_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

Instance Method Details

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


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/wicked_pdf.rb', line 32

def pdf_from_string(string, options={})
  string_file = WickedPdfTempfile.new("wicked_pdf.html")
  string_file.write(string)
  string_file.close

  generated_pdf_file = WickedPdfTempfile.new("wicked_pdf_generated_file.pdf")
  command = "\"#{@exe_path}\" #{'-q ' unless on_windows?}#{parse_options(options)} \"file://#{string_file.path}\" \"#{generated_pdf_file.path}\" " # -q for no errors on stdout
  print_command(command) if in_development_mode?
  err = Open3.popen3(command) do |stdin, stdout, stderr|
    stderr.read
  end
  generated_pdf_file.rewind
  generated_pdf_file.binmode
  pdf = generated_pdf_file.read
  raise "PDF could not be generated!" if pdf and pdf.rstrip.length == 0
  pdf
rescue Exception => e
  raise "Failed to execute:\n#{command}\nError: #{e}"
end