Sha256: a9722e28270b795e7941fb555bc9842c4d2832ae534dde6f6d28c015f22ed522

Contents?: true

Size: 1.25 KB

Versions: 1

Compression:

Stored size: 1.25 KB

Contents

# frozen_string_literal: true

require 'chrome_remote'

module Postdoc
  class Client
    attr_accessor :client

    def initialize(port)
      @port = port
      100.times { setup_connection_or_wait && break }
      raise 'ChromeClient couldn\'t launch' if @client.blank?
    end

    def print_pdf_from_html(file_path,
        header_template: false,
        footer_template: false,
        **options)

      client.send_cmd 'Page.enable'
      client.send_cmd 'Page.navigate', url: "file://#{file_path}"
      client.wait_for 'Page.loadEventFired'

      response = client.send_cmd 'Page.printToPDF', {
        landscape: options[:landscape] || false,
        printBackground: true,
        marginTop: options[:margin_top] || 1,
        marginBottom: options[:margin_bottom] || 1,
        marginLeft: options[:margin_left] || 1,
        marginRight: options[:margin_right] || 1,
        displayHeaderFooter: !!(header_template || footer_template),
        headerTemplate: header_template || '',
        footerTemplate: footer_template || ''
      }

      Base64.decode64 response['data']
    end

    private

    def setup_connection_or_wait
      @client = ChromeRemote.client(port: @port)
      true
    rescue Exception
      sleep(0.1)
      false
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
postdoc-0.3.6 lib/postdoc/client.rb