windows - 使用 Phantom JS 将文件夹中的所有 HTML 文件转换为 PNG

标签 windows png phantomjs

我已经开始在 Windows 上使用 Phantom JS,但我很难找到有关其功能的文档(可能是我问题的根源)。

使用 Phantom JS 我想做以下事情:

  1. 给它一个本地机器文件夹位置,
  2. 让它导航到该位置并识别 HTML 文件列表,
  3. 一旦该列表被识别为循环 HTML 文件列表并将它们全部转换为 PNG(类似于 rasterize.js 示例的工作方式),其中文件名 gsubs“HTML”和“PNG”。

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

  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++;
}

希望这对您有所帮助。有关文件系统调用的更多信息,请查看此页面:http://phantomjs.org/api/fs/

此外,我想补充一点,我相信 FileSystem 函数仅在 PhantomJS 1.3 或更高版本中可用。请确保运行 latest版本。我在 Windows 上使用了 PyPhantomJS,但我确信它在其他系统上也能正常工作。

关于windows - 使用 Phantom JS 将文件夹中的所有 HTML 文件转换为 PNG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7531601/

相关文章:

C 在 linux 和 windows 上获取 cpu 使用率

windows - 在 MS 窗口中执行 .java

.net - 在 .NET 中将元数据写入 PNG 图像

javascript - PhantomJS:无法通过单击或提交来提交输入

javascript - 有没有办法从 PhantomJS 的键盘读取用户输入?

windows - Git 对 POSIX 功能的依赖在 Windows 上仍然是一个问题吗?

java - 如何在Python中检查Windows中 "start"命令启动的程序的输出?

linux - 使用 Inkscape 将带有自定义字体的 SVG 转换为 PNG

c# - 在代码中将透明PNG转换为System.Drawing.Icon

angularjs - 等待 Angular 应用程序从幻像脚本中完全呈现