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
36
# 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'
  }
  @wkhtmltopdf= options[:exe] if options[:exe]
  options.delete(:exe)
  @options = normalize_options(default_options.merge(options))
  
  raise NoExecutableError.new if wkhtmltopdf.nil? || wkhtmltopdf == ''
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



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

def command
  args = [wkhtmltopdf]
  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



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

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

#to_pdfObject



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

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