一各薇、新建項目
rails new app --skip-bundle
完成后修改Gemfile文件:vim Gemfile
把source 修改成taobao或者ruby-china的源。
在這個文件里加入:gem 'phantomjs'
然后運行:bundle install
這樣項目就新建完成了娩贷。
phantomjs需要單獨下載纬乍,如果不下載碱茁,這個gem運行的時候會自動下載,可能會比較慢仿贬。
二纽竣、生成pdf
創(chuàng)建一個controller在頭部加上require 'phantomjs'
在format.pdf的代碼塊里中入如下代碼:
url = "http://webdomain/path" #這是要生成pdf的頁面url
name = "#{Time.now.to_date.to_s(:db)}_#{Digest::MD5.hexdigest('pdf'+Time.now.to_i.to_s)}.pdf"
path = Rails.root.join("public","download", "#{name}").to_s #生成pdf后存放的路徑
Phantomjs.base_dir = Rails.root.join('public','js', 'phantomjs').to_s # 這里是下載phantomjs文件的存放路徑,如果不指定這個,它會自動下載phantomjs。
Phantomjs.run(Rails.root.join('public','js','rasterize.js').to_s, url, path, "", request.host, cookies["_your_session"]) #resterize.js存入在public/js下蜓氨, _your_session是你的項目的session名稱聋袋。
send_file(path)
這里使用的是resterize.js,需要對源碼進行修改:
"use strict";
var page = require('webpage').create(),
system = require('system'),
address, output, size;
phantom.addCookie({
'name'???? : '_your_session',?? /* 你的session 名稱? */
'value'??? : system.args[5],? /* session ,傳入的參數(shù)*/
'domain'?? : system.args[4],? /* 你的域名语盈,傳入的參數(shù) */
'path'???? : '/',??????????????? /* required property */
'httponly' : true,
'secure'?? : false,
'expires'? : (new Date()).getTime() + (1000 * 60 * 60)?? /* <-- expires in 1 hour */
});
if (system.args.length < 3 || system.args.length > 6) {
console.log('Usage: rasterize.js URL filename [paperwidth*paperheight|paperformat] [zoom]');
console.log('? paper (pdf output) examples: "5in*7.5in", "10cm*20cm", "A4", "Letter"');
console.log('? image (png/jpg output) examples: "1920px" entire page, window width 1920px');
console.log('?????????????????????????????????? "800px*600px" window, clipped to 800x600');
phantom.exit(1);
} else {
address = system.args[1];
output = system.args[2];
page.viewportSize = { width: 600, height: 600 };
// if (system.args.length > 4) {
//???? page.zoomFactor = 0.1;
// }
page.open(address, function (status) {
if (status !== 'success') {
console.log('Unable to load the address!');
phantom.exit(1);
} else {
window.setTimeout(function () {
page.render(output);
phantom.exit();
}, 1000);
}
});
}
本例主要是生成pdf舱馅,去掉了一些沒用的代碼,加入了addCookie的代碼刀荒。