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
62
63
64
65
66
|
# File 'lib/puppeteer_pdf.rb', line 18
def self.generate_pdf(url, output_file_path ,opts = {})
include_page_numbers = opts[:include_page_numbers] || true
random_string = generate_random_string
page_height = opts[:height] || 600
page_width = opts[:width] || 1125
page_layout = opts[:layout] || ''
print_background = opts[:print_background] || true
= opts[:header_text] || ''
= opts[:footer_text] || ''
format = opts[:format] || ''
timeout = opts[:timeout] || 0
color_coding("PuppeteerPdf ERROR : height must be Integer", 'red') unless page_height.class == Integer
color_coding("PuppeteerPdf ERROR : widgth must be Integer", 'red') unless page_width.class == Integer
color_coding("PuppeteerPdf ERROR : layout must be between ['Landscape']", 'red') unless ['Landscape', ''].include?(page_layout)
color_coding("PuppeteerPdf ERROR : print_background must be Boolean", 'red') unless [TrueClass, FalseClass].include?(print_background.class)
color_coding("PuppeteerPdf ERROR : header_text must be String", 'red') unless .class == String
color_coding("PuppeteerPdf ERROR : footer_text must be String", 'red') unless .class == String
color_coding("PuppeteerPdf ERROR : timeout must be Integer", 'red') unless timeout.class == Integer
color_coding("PuppeteerPdf ERROR : format must be between ['A4']", 'red') unless ['A4', ''].include?(format)
color_coding("PuppeteerPdf ERROR : include_page_numbers must be Boolean", 'red') unless [TrueClass, FalseClass].include?(include_page_numbers.class)
= ( == '' && == '') == true ? false : true
raise "INVALID PATH, Hint : (/path/file.pdf)" unless output_file_path.include?('.pdf')
temp_path = output_file_path.reverse.split('/',2)[1].reverse
tmp_js_file_name = "#{temp_path}/puppeteer_#{random_string}.js"
js_code = "const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setViewport({ width: #{page_width}, height: #{page_height} })
await page.goto('#{url}', {waitUntil: 'networkidle2', timeout: #{timeout}});
await page.pdf({path: '#{output_file_path}', format: '#{format}', width: '#{page_width}px', height: '#{page_height}px', layout: '#{page_layout}' , printBackground: #{print_background}, displayHeaderFooter: #{},
margin: {top: 10, bottom: 40}, headerTemplate: '<span>#{}</span>' });
await browser.close();
})();"
file = File.open(tmp_js_file_name, "w")
file.puts js_code
file.close
system("node #{tmp_js_file_name}") system("rm -rf #{tmp_js_file_name}")
color_coding("############################################################################################################", 'blue')
color_coding("PDF IS GENERATED : #{output_file_path}", 'green')
color_coding("############################################################################################################", 'blue')
output_file_path
end
|