【问题标题】:Schedule PDF generation with phantom.js and node.js使用 phantom.js 和 node.js 安排 PDF 生成
【发布时间】:2016-06-30 06:38:58
【问题描述】:

我是 node.js 和 phantom.js 的新手,所以我不确定如何比我在下面所做的更好地利用它们。

我有 100 所学校的着装价格表,可以从相应的学校页面下载为 PDF 格式。我们所做的是生成 PDF 并在一夜之间上传到服务器。

现在我们想使用 node.js 和 phantom.js 批量生成 PDF 并尽可能自动化该过程。

下面的链接不是价目表页面,而是用于测试 PDF 的示例 URL。

```

var schedule = require('node-schedule'),
    path = require('path'),
    childProcess = require('child_process'),
    phantomjs = require('phantomjs'),
    binPath = phantomjs.path,
    childArgs = [
        // phantomjs rasterize.js http://codefight.org codefight.pdf
        path.join(__dirname, 'rasterize.js'),
            'http://codefight.org/',
            'codefight.pdf',
            '400*300'
        ]

// add all the URLs and name of PDF here
var pdfSources = [
            ['codefight.pdf', 'http://codefight.org/'],
            ['dltr.pdf', 'http://dltr.org/']
        ];

// schedule generating PDFs
// running every minute for now to test
var j = schedule.scheduleJob('* * * * *', function(){

  // loop through the pdfSources and generate new PDFs
  pdfSources.forEach(function(item, index){

    // update childArgs
    childArgs[1] = item[1]; // pdf content source url
    childArgs[2] = item[0]; // pdf filename

    childProcess.execFile(binPath, childArgs, function(err, stdout, stderr) {
        // for some reason childArgs[2] always prints last item of pdfSources
        // not sure how to make it work :(
        console.log('New PDF - "' + childArgs[2] + '" generated!');
        console.log(err + stdout + stderr);
    });
  });
});

```

1. 我想知道为什么console.log('New PDF - "' + childArgs[2] + '" generated!'); 总是打印相同的输出。即“新 PDF - “dltr.pdf”生成!”

2. 是否有更好的方法来使用 node.js 和 phantom.js 实现相同的目标以及您想提出的任何改进建议?

谢谢!

【问题讨论】:

    标签: javascript node.js performance pdf phantomjs


    【解决方案1】:

    答案 1。由于execFile 的异步性质,输出相同。因此,基本上在forEach 循环中,您将值分配给childArgs[2] 并调用execFile,但它的回调被放入队列中,然后在第二个循环中您覆盖childArgs[2] 并再次调用execFile。现在是运行回调的时候了,但问题是 childArgs[2] 具有您分配给它的最后一个值。解决方法可能是将 execFile 放在像下面这样的闭包中

    (function(cArgs){
    
          childProcess.execFile(binPath, cArgs, function(err, stdout, stderr) { 
              console.log('New PDF - "' + cArgs[2] + '" generated!');       
              console.log(err + stdout + stderr); 
          });
    
    })(childArgs);
    

    我对问题 2 没有什么要补充的。

    【讨论】:

    • 谢谢。经过测试但结果相同。
    • 嗯,很奇怪。您可以在(function(cArgs){ 下方添加console.log(cArgs);,您是否真的创建了2 个不同的PDF 文件?
    • 是的 2 个不同的 PDF 文件使用正确的内容创建。但控制台只显示最后的数据。
    • 你试过console.log(cArgs)吗?
    猜你喜欢
    • 1970-01-01
    • 2017-06-15
    • 1970-01-01
    • 2015-07-09
    • 1970-01-01
    • 2017-10-15
    • 2013-06-10
    • 2018-02-13
    • 2018-05-19
    相关资源
    最近更新 更多