Sha256: 37387a39081935d9c6a6c732f1f4d025b6076ba74dda752b455e91bf9ea9b23f

Contents?: true

Size: 1.54 KB

Versions: 1

Compression:

Stored size: 1.54 KB

Contents

require 'postdoc/postdoc_view_helper'
require 'chrome_remote'

module Postdoc

  class PostdocRailtie < Rails::Railtie
    initializer 'postdoc.register' do |_app|
      ActionView::Base.send :include, PostdocViewHelper
    end
  end

  ActionController::Renderers.add :pdf do |filename, options|
    htmlfile = Tempfile.new ['input', '.html']

    htmlfile.write render_to_string(options)
    htmlfile.flush

    # random port at 1025 or higher
    random_port = 1024 + Random.rand(65535 - 1024)

    pid = Process.spawn "chrome --remote-debugging-port=#{random_port} --headless"

    # FIXME
    sleep 1

    begin
      chrome = ChromeRemote.client port: random_port
      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?
        displayHeaderFooter = true
      else
        displayHeaderFooter = 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: displayHeaderFooter,
        headerTemplate: options[:header_template],
        footerTemplate: options[:footer_template]
      }
      result = Base64.decode64 response['data']
    ensure
      Process.kill 'KILL', pid
      Process.wait pid

      htmlfile.close
      htmlfile.unlink
    end

    result
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
postdoc-0.2.1 lib/postdoc.rb