使用Phantom JS将文件夹中的所有HTML文件转换为PNG [英] Using Phantom JS to convert all HTML files in a folder to PNG

查看:37
本文介绍了使用Phantom JS将文件夹中的所有HTML文件转换为PNG的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开始在Windows上使用Phantom JS,但是在查找有关其功能的文档时遇到了一些困难(可能是问题的根源).

I've started using Phantom JS on Windows, but I'm having a bit of difficulty finding documentation on its capability (probably the root of my problem).

使用Phantom JS,我想执行以下操作:

Using Phantom JS I would like to do the following:

  1. 为其提供本地计算机文件夹位置,
  2. 让它导航到该位置并识别HTML文件列表
  3. 一旦识别出该列表即可循环HTML文件列表并将其全部转换为PNG(类似于rasterize.js示例的工作方式),其中文件名gsubs带有"PNG"的"HTML".

我确定这可能是可行的,但是我找不到Phantom JS函数调用:

I'm sure this is probably possible, but I wasn't able to find the Phantom JS function call for:

  1. 获取文件夹中的文件列表和
  2. Phantom JS中gsub和grep的格式.

推荐答案

var page = require('webpage').create(), loadInProgress = false, fs = require('fs');
var htmlFiles = new Array();
console.log(fs.workingDirectory);
var curdir = fs.list(fs.workingDirectory);

// loop through files and folders
for(var i = 0; i< curdir.length; i++)
{
    var fullpath = fs.workingDirectory + fs.separator + curdir[i];
    // check if item is a file
    if(fs.isFile(fullpath))
    {
        // check that file is html
        if(fullpath.indexOf('.html') != -1)
        {
            // show full path of file
            console.log('File path: ' + fullpath);
            htmlFiles.push(fullpath);
        }
    }
}

console.log('Number of Html Files: ' + htmlFiles.length);

// output pages as PNG
var pageindex = 0;

var interval = setInterval(function() {
    if (!loadInProgress && pageindex < htmlFiles.length) {
        console.log("image " + (pageindex + 1));
        page.open(htmlFiles[pageindex]);
    }
    if (pageindex == htmlFiles.length) {
        console.log("image render complete!");
        phantom.exit();
    }
}, 250);

page.onLoadStarted = function() {
    loadInProgress = true;
    console.log('page ' + (pageindex + 1) + ' load started');
};

page.onLoadFinished = function() {
    loadInProgress = false;
    page.render("images/output" + (pageindex + 1) + ".png");
    console.log('page ' + (pageindex + 1) + ' load finished');
    pageindex++;
}

希望此帮助.有关FileSystem调用的更多信息,请查看以下页面: http://phantomjs.org/api/fs/

Hope this helps. For more information about the FileSystem calls, check this page out: http://phantomjs.org/api/fs/

我还想补充一点,我相信FileSystem函数仅在PhantomJS 1.3或更高版本中可用.请确保运行最新版本.我在Windows上使用了PyPhantomJS,但我确信它在其他系统上也不会出现问题.

Also, I wanted to add, that I believe the FileSystem functions are only available in PhantomJS 1.3 or later. Please make sure to run the latest version. I used PyPhantomJS for Windows but I'm sure this will work without a hitch on other systems as well.

这篇关于使用Phantom JS将文件夹中的所有HTML文件转换为PNG的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆