Skip to content

Instantly share code, notes, and snippets.

@mcastilho
Forked from boriscy/incomes_controller.rb
Created July 7, 2017 22:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcastilho/21f8f9b842f2a2441a2e933b3e5647d6 to your computer and use it in GitHub Desktop.
Save mcastilho/21f8f9b842f2a2441a2e933b3e5647d6 to your computer and use it in GitHub Desktop.
Print to PDF using phantomjs
# Example controller
class IncomesController < ApplicationController
# Include the print
include Controllers::Print
# GET /incomes/1
def show
@income = present Income.find(params[:id])
respond_to do |format|
format.html
format.print
format.pdf { print_pdf 'show.print', "Income-#{@income}" }
end
end
end
// app/asseets/javascripts/print/print.js
var page = require('webpage').create(),
system = require('system'),
fs = require('fs'),
page = require('webpage').create(),
address, output, size;
// This is the print that phantomjs runs
page.viewportSize = { width: 600, height: 600 };
page.paperSize = {
format: 'A4'
}
file = system.args[1];
pdf = system.args[2];
html = fs.read(file);
page.content = html;
// '<style>h1{ font-weight: normal; }</style><h1>This is a test, jejejeje</h1>';
page.onLoadFinished = function() {
page.render(pdf);
phantom.exit();
}
# lib/controllers/print.rb
module Controllers::Print
private
def print_pdf(template, name)
html = render_to_string template, layout: 'application.print'
save_and_generate_pdf html
# send_file
#send_file File.read("#{full_path_name}.pdf"), filename: "#{name}.pdf"
send_file "#{full_path_name}.pdf", filename: "#{name}.pdf"
end
def save_and_generate_pdf(html)
save_printed html
generate_phantom_pdf
end
def save_printed(html)
f = File.new("#{full_path_name}.html", 'w+')
f.write(html)
f.close
end
def print_name
@print_name ||= SecureRandom.urlsafe_base64
end
def full_path_name
@full_path_name ||= "/tmp/#{print_name}"
end
def generate_phantom_pdf
script = Rails.root.join('app', 'assets', 'javascripts', 'print', 'print.js')
%x[phantomjs #{script} #{full_path_name}.html #{full_path_name}.pdf]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment