Class: PDFKit

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

Defined Under Namespace

Classes: ImproperSourceError, Middleware, NoExecutableError, Source

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of PDFKit.

Raises:



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/pdfkit/pdfkit.rb', line 18

def initialize(url_file_or_html, options = {})
  @source = Source.new(url_file_or_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

#optionsObject (readonly)

Returns the value of attribute options.



16
17
18
# File 'lib/pdfkit/pdfkit.rb', line 16

def options
  @options
end

#sourceObject

Returns the value of attribute source.



15
16
17
# File 'lib/pdfkit/pdfkit.rb', line 15

def source
  @source
end

#stylesheetsObject

Returns the value of attribute stylesheets.



15
16
17
# File 'lib/pdfkit/pdfkit.rb', line 15

def stylesheets
  @stylesheets
end

Instance Method Details

#commandObject



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

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

#to_file(path) ⇒ Object



63
64
65
# File 'lib/pdfkit/pdfkit.rb', line 63

def to_file(path)
  File.open(path,'w') {|file| file << self.to_pdf}
end

#to_pdfObject



52
53
54
55
56
57
58
59
60
61
# File 'lib/pdfkit/pdfkit.rb', line 52

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