forked from ManageIQ/manageiq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpdf_generator.rb
55 lines (45 loc) · 1.57 KB
/
pdf_generator.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
class PdfGenerator
def self.new
self == PdfGenerator ? detect_available_generator.new : super
end
def self.instance
@instance ||= self.new
end
def self.pdf_from_string(html_string, stylesheet)
instance.pdf_from_string(sanitize_html(html_string), stylesheet_file_path(stylesheet))
end
def self.available?
instance.available?
end
# Convert `html_string` to pdf using the given css `stylesheet`
#
# @param [String] html_string The HTML content to be converted to pdf
# @param [String] stylesheet File name (without extension) of the css
# stylesheet to be used
# @return [String] The pdf file contents
def pdf_from_string(_html_string, _stylesheet)
raise NotImplementedError, "must be implemented in a subclass"
end
def available?
self.class.available?
end
def self.detect_available_generator
self.subclasses.detect(&:available?) || NullPdfGenerator
end
private_class_method :detect_available_generator
def self.sanitize_html(html_string)
# strip out bad attachment_fu URLs
# and remove asset ids on images
html_string.gsub('.com:/', '.com/')
.gsub(/src=["'](\S+)\?\d*["']/i, 'src="\1"')
end
private_class_method :sanitize_html
# Find stylesheet asset with short path and return filesystem path
#
def self.stylesheet_file_path(stylesheet)
Rails.application.assets.find_asset(stylesheet).try(:pathname).try(:to_s)
end
private_class_method :stylesheet_file_path
end
# Dynamically load all plugins
Dir.glob(File.join(File.dirname(__FILE__), "pdf_generator/*.rb")).each { |f| require_dependency f }