Skip to content

Instantly share code, notes, and snippets.

@Jpuelpan
Last active October 30, 2018 13:17
Show Gist options
  • Save Jpuelpan/7895391 to your computer and use it in GitHub Desktop.
Save Jpuelpan/7895391 to your computer and use it in GitHub Desktop.
A very simple Ruby wrapper for PhantomJS.
# exporter.rb
# A very simple Ruby wrapper for PhantomJS
# for create PDF's or anything you can create with PhantomJS
require 'json'
class Exporter
class PhantomJSNotFound < StandardError; end
class << self
def default_options
{
format: 'A4',
orientation: 'portrait',
border: '1cm',
rasterize_bin: File.dirname(__FILE__) + '/rasterize.js',
phantomjs_bin: Exporter.phantomjs_bin,
timeout: 1000,
headers: nil
}
end
def phantomjs_bin
bin_path = (`which phantomjs`).to_s.chomp
raise Exporter::PhantomJSNotFound if bin_path.empty?
bin_path
end
end
def initialize(url, output, options = {})
@url = url
@output = output
@default_options = Exporter.default_options.merge(options)
execute
end
def file_path
@output
end
def file
File.open(@output)
end
private
def execute
cmd = @default_options[:phantomjs_bin]
cmd += " #{@default_options[:rasterize_bin]}"
cmd += " --url=#{@url}"
cmd += " --output=#{@output}"
cmd += " --format=#{@default_options[:format]}"
cmd += " --orientation=#{@default_options[:orientation]}"
cmd += " --border=#{@default_options[:border]}"
cmd += " --timeout=#{@default_options[:timeout]}"
cmd += " --headers='#{@default_options[:headers].to_json}'" unless @default_options[:headers].nil?
`#{cmd}`
end
end
var system = require('system')
, page = require('webpage').create()
, args = {};
if( system.args.length > 1 ){
for( var i = 1; i < system.args.length; i++ ){
var params = system.args[i].split('='),
key = params[0].replace('--', ''),
value = params[1];
if( key == 'headers' ){
args[key] = JSON.parse(value);
}else{
args[key] = value;
}
}
}
page.paperSize = {
format: args.format,
orientation: args.orientation,
border: args.border
};
if( args.hasOwnProperty('headers') ){
page.customHeaders = args.headers;
}
page.open(args.url, function (status) {
if(status !== 'success') {
console.log('Unable to access the network!');
phantom.exit(1);
}else{
setTimeout(function(){
page.render(args.output);
phantom.exit();
}, args.timeout);
}
});
@Jpuelpan
Copy link
Author

Node.JS is required, after installed it, proceed with the installation of PhantomJS:

npm install -g phantomjs

Then from Ruby, in this case a Rails controller:

def export
  pdf = Exporter.new('http://google.cl', '/home/user/google.pdf')
  send_file(pdf.file_path, filename: 'Google', type: 'application/pdf', disposition: 'inline')
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment