rails new app --skip-bundlecss
完成後修改Gemfile文件:vim Gemfileweb
把source 修改爲taobao或者ruby-china的源。vim
在這個文件里加入:gem 'phantomjs'ruby
而後運行:bundle installapp
這樣項目就新建完成了。ui
建立一個controller在頭部加上require 'phantomjs',在裏面加入一個獲取pdf的get方法:get_pdf圖片
在這個方法里加入以下代碼:ip
Phantomjs.base_dir = "/path/project_name/bin/phantomjs/" #phantomjs將要安裝的目錄
Phantomjs.run('/path/project_name/public/generate_pdf.js')get
send_file("public/mypdf.pdf", :filename => "mypdf.pdf", :type => "application/pdf")it
在generate_pdf.js加入以下代碼:
var page = require('webpage').create();
page.open('http://www.baidu.com');
page.onLoadFinished = function() {
page.render('public/mypdf.pdf');
phantom.exit();
}
啓動服務:rails s
在地址欄裏輸入http://localhost:3000/controller/get_pdf
第一次請求這個方法,會安裝phantomjs到/path/project_name/bin/phantomjs/這個目錄。
等安裝完成後,就能夠看到保存要下的pdf了:
這樣這成功了。
注意:這樣導出的pdf不包含css樣式裏的背景和背景圖片。