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
56
57
58
59
60
61
|
# File 'lib/postdoc.rb', line 10
def self.render_from_string(string, options)
htmlfile = Tempfile.new ['input', '.html']
htmlfile.write string
htmlfile.flush
if options[:client].nil?
random_port = 1024 + Random.rand(65_535 - 1024)
pid = Process.spawn "chrome --remote-debugging-port=#{random_port} --headless"
end
sleep 1
begin
chrome = options[:client].nil? ? ChromeRemote.client(port: random_port) : options[:client]
chrome.send_cmd 'Page.enable'
chrome.send_cmd 'Page.navigate', url: "file://#{htmlfile.path}"
chrome.wait_for 'Page.loadEventFired'
if options[:header_template].present? || options[:footer_template].present?
= true
else
= false
end
response = chrome.send_cmd 'Page.printToPDF', {
landscape: options[:landscape] || false,
printBackground: true,
marginTop: options[:margin_top] || 1,
marginBottom: options[:margin_bottom] || 1,
displayHeaderFooter: ,
headerTemplate: options[:header_template] || '',
footerTemplate: options[:footer_template] || ''
}
result = Base64.decode64 response['data']
ensure
if options[:client].nil?
Process.kill 'KILL', pid
Process.wait pid
else
chrome.send_cmd 'Page.close'
end
htmlfile.close
htmlfile.unlink
end
result
end
|