美文网首页我爱编程
ruby on rails 中使用phantomjs,并使用co

ruby on rails 中使用phantomjs,并使用co

作者: limx | 来源:发表于2017-03-25 21:54 被阅读0次

    一、新建项目

    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,并使用co

        本文链接:https://www.haomeiwen.com/subject/deqhottx.html