窗口 – 使用Phantom JS将文件夹中的所有HTML文件转换为PNG

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

使用Phantom JS我想做以下:

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

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

>获取文件夹中的文件列表
> 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++;
}

希望这个helps.有关FileSystem调用的更多信息,请查看此页面https://github.com/ariya/phantomjs/wiki/API-Reference

此外,我想补充说,我相信FileSystem功能仅在PhantomJS 1.3或更高版本中可用.请确保运行latest版本.我使用PyPhantomJS Windows,但我确信这将工作,而不妨碍其他系统.

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...