Class: PDFKit

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

Defined Under Namespace

Classes: Middleware, NoExecutableError

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(html, options = {}) ⇒ PDFKit

Returns a new instance of PDFKit.

Raises:



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/pdfkit/pdfkit.rb', line 12

def initialize(html, options = {})
  @html = html
  @stylesheets = []
  
  default_options = {
    :disable_smart_shrinking => true,
    :page_size => 'Letter',
    :margin_top => '0.75in',
    :margin_right => '0.75in',
    :margin_bottom => '0.75in',
    :margin_left => '0.75in'
  }
  @options = normalize_options(options.reverse_merge(default_options))
  
  @cmd  = `which wkhtmltopdf-proxy`.chomp
  raise NoExecutableError.new if @cmd.blank?
end

Instance Attribute Details

#htmlObject

Returns the value of attribute html.



9
10
11
# File 'lib/pdfkit/pdfkit.rb', line 9

def html
  @html
end

#optionsObject (readonly)

Returns the value of attribute options.



10
11
12
# File 'lib/pdfkit/pdfkit.rb', line 10

def options
  @options
end

#stylesheetsObject

Returns the value of attribute stylesheets.



9
10
11
# File 'lib/pdfkit/pdfkit.rb', line 9

def stylesheets
  @stylesheets
end

Instance Method Details

#commandObject



30
31
32
33
34
35
36
37
# File 'lib/pdfkit/pdfkit.rb', line 30

def command
  args = [@cmd]
  args += @options.to_a.flatten.compact
  args << '--quiet'
  args << '-' # Get HTML from stdin
  args << '-' # Read PDF from stdout
  args.join(' ')
end

#to_pdfObject



39
40
41
42
43
44
45
46
47
48
# File 'lib/pdfkit/pdfkit.rb', line 39

def to_pdf
  append_stylesheets
  
  pdf = IO.popen(command, "w+")
  pdf.puts(@html)
  pdf.close_write
  result = pdf.gets(nil)
  pdf.close_read
  return result
end