標籤:== 代碼 load 需要 iges viewport bpa dir res
一、建立項目
rails new app --skip-bundle
完成後修改Gemfile檔案:vim Gemfile
把source 修改成taobao或者ruby-china的源。
在這個檔案裡加入:gem ‘phantomjs‘
然後運行:bundle install
這樣項目就建立完成了。
phantomjs需要單獨下載,如果不下載,這個gem啟動並執行時候會自動下載,可能會比較慢。
二、產生pdf
建立一個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 ,傳入的參數*/
‘domain‘ : system.args[4], /* 你的網域名稱,傳入的參數 */
‘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的代碼。
ruby on rails 中使用phantomjs,並使用cookie