Last active
October 14, 2017 08:05
-
-
Save boriscy/a0ac26c54f30296949df to your computer and use it in GitHub Desktop.
Print to PDF using phantomjs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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