Class: HTML2PDFChrome::HtmlConverter

Inherits:
Object
  • Object
show all
Defined in:
lib/html2pdf_chrome/html_converter.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(html, header_template: "<div></div>", footer_template: "<div></div>") ⇒ HtmlConverter

Returns a new instance of HtmlConverter.



5
6
7
8
9
# File 'lib/html2pdf_chrome/html_converter.rb', line 5

def initialize(html, header_template: "<div></div>", footer_template: "<div></div>")
  @html = html
  @header_template = header_template
  @footer_template = footer_template
end

Instance Attribute Details

Returns the value of attribute footer_template.



3
4
5
# File 'lib/html2pdf_chrome/html_converter.rb', line 3

def footer_template
  @footer_template
end

#header_templateObject (readonly)

Returns the value of attribute header_template.



3
4
5
# File 'lib/html2pdf_chrome/html_converter.rb', line 3

def header_template
  @header_template
end

#htmlObject (readonly)

Returns the value of attribute html.



3
4
5
# File 'lib/html2pdf_chrome/html_converter.rb', line 3

def html
  @html
end

Instance Method Details

#convert_to_pdf!Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/html2pdf_chrome/html_converter.rb', line 11

def convert_to_pdf!
  encoded_html = Base64.strict_encode64(html)
  data_url = "data:text/html;base64,#{encoded_html}"

  pdf_data = nil
  Chromedriver.fetch_driver do |driver|
    driver.navigate.to(data_url)
    cdp_response = driver.execute_cdp(
      'Page.printToPDF',
      displayHeaderFooter: true,
      printBackground: true,
      headerTemplate: header_template,
      footerTemplate: footer_template,
    )
    pdf_data = Base64.decode64(cdp_response['data'])
  end
  pdf_data
end