Class: Wkhtmltopdf

Inherits:
Object
  • Object
show all
Defined in:
lib/to_pdf/wkhtmltopdf.rb

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.asset_domain=(domain) ⇒ Object (writeonly)

Sets the attribute asset_domain

Parameters:

  • value

    the value to set the attribute asset_domain to.



3
4
5
# File 'lib/to_pdf/wkhtmltopdf.rb', line 3

def asset_domain=(value)
  @asset_domain = value
end

.executable_path=(path) ⇒ Object (writeonly)

Sets the attribute executable_path

Parameters:

  • value

    the value to set the attribute executable_path to.



3
4
5
# File 'lib/to_pdf/wkhtmltopdf.rb', line 3

def executable_path=(value)
  @executable_path = value
end

Class Method Details

.detect_executable_pathObject



13
14
15
16
17
# File 'lib/to_pdf/wkhtmltopdf.rb', line 13

def detect_executable_path
  IO.popen('which wkhtmltopdf') { |pipe| @executable_path = pipe.gets }
  raise 'Cannot find command `wkhtmltopdf` in $PATH' unless @executable_path
  @executable_path.strip!
end


57
58
59
60
61
# File 'lib/to_pdf/wkhtmltopdf.rb', line 57

def extract_footer_url(string)
  footer_url = nil
  string.scan(/<meta [^>]*>/).each { |meta| footer_url = meta.scan(/content=["']([^"']*)/)[0][0] unless meta.scan(/name="footer"/).empty?}
  footer_url
end

.extract_header_url(string) ⇒ Object



51
52
53
54
55
# File 'lib/to_pdf/wkhtmltopdf.rb', line 51

def extract_header_url(string)
  header_url = nil
  string.scan(/<meta [^>]*>/).each { |meta| header_url = meta.scan(/content=["']([^"']*)/)[0][0] unless meta.scan(/name="header"/).empty?}
  header_url
end

.localise_paths(string) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/to_pdf/wkhtmltopdf.rb', line 38

def localise_paths(string)
  string.gsub!('src="/', "src=\"#{Rails.public_path}/") if defined?(Rails)

  if @asset_domain
    string.gsub!('link href="/', "link href=\"#{@asset_domain}/")
  elsif defined?(Rails)
    string.gsub!('link href="/', "link href=\"#{Rails.public_path}/")
    string.gsub!('url(/', "url(#{Rails.public_path}/")
  end

  string
end

.string_to_pdf(string) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/to_pdf/wkhtmltopdf.rb', line 19

def string_to_pdf(string)
  detect_executable_path unless @executable_path

  header = extract_header_url(string)
  footer = extract_footer_url(string)

  pdf = IO.popen(wkhtmltopdf_command(header, footer), 'w+')
  pdf.puts(localise_paths(string))
  pdf.close_write
  result = pdf.gets(nil)
  pdf.close_read

  result
end

.wkhtmltopdf_command(header, footer) ⇒ Object



34
35
36
# File 'lib/to_pdf/wkhtmltopdf.rb', line 34

def wkhtmltopdf_command(header, footer)
  "#{@executable_path} -q --allow #{Rails.public_path}#{" --header-html '#{header}'" if header}#{" --footer-html '#{footer}'" if footer} - - "
end