Class: Palapala::Pdf

Inherits:
Object
  • Object
show all
Defined in:
lib/palapala/pdf.rb

Overview

Page class to generate PDF from HTML content using Chrome in headless mode in a thread-safe way

Instance Method Summary collapse

Constructor Details

#initialize(content = nil, url: nil, path: nil, header_html: nil, footer_html: nil, generate_tagged_pdf: false, prefer_css_page_size: true, scale: Palapala.defaults.fetch(:scale, 1), page_ranges: Palapala.defaults.fetch(:page_ranges, ''), margin: Palapala.defaults.fetch(:margin, {})) ⇒ Pdf

Returns a new instance of Pdf.



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/palapala/pdf.rb', line 8

def initialize(content = nil,
               url: nil,
               path: nil,
               header_html: nil,
               footer_html: nil,
               generate_tagged_pdf: false,
               prefer_css_page_size: true,
               scale: Palapala.defaults.fetch(:scale, 1),
               page_ranges: Palapala.defaults.fetch(:page_ranges, ''),
               margin: Palapala.defaults.fetch(:margin, {}))
  @content = content
  @url = url
  @path = path
  @header_html = header_html
  @footer_html = footer_html
  @generate_tagged_pdf = generate_tagged_pdf
  @prefer_css_page_size = prefer_css_page_size
  @page_ranges = page_ranges
  @scale = scale
  @margin = margin
end

Instance Method Details

#binary_data(**opts) ⇒ Object



52
53
54
# File 'lib/palapala/pdf.rb', line 52

def binary_data(**opts)
  pdf(**opts)
end

#pdf(**opts) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/palapala/pdf.rb', line 30

def pdf(**opts)
  browser_context = browser.contexts.create
  browser_page = browser_context.page
  # # output console logs for this page
  if opts[:debug]
    browser_page.on('Runtime.consoleAPICalled') do |params|
      params['args'].each { |r| puts(r['value']) }
    end
  end
  # open the page
  url = @url || data_url
  browser_page.go_to(url)
  # Wait for the page to load
  browser_page.network.wait_for_idle
  # Generate PDF
  pdf_binary_data = browser_page.pdf(**opts_with_defaults.merge(opts))
  # Dispose the context
  browser_context.dispose
  # Return the PDF data
  pdf_binary_data
end

#save(path, **opts) ⇒ Object



56
57
58
# File 'lib/palapala/pdf.rb', line 56

def save(path, **opts)
  pdf(path:, **opts)
end