电脑应用png转化为html,使用Phantom JS将文件夹中的所有HTML文件转换为PNG

这段代码展示了如何使用PhantomJS的FileSystem API遍历目录,查找HTML文件,并将它们渲染为PNG。它利用`webpage`模块创建网页实例,通过定时器依次打开和保存每个HTML文件的截图。适合学习PhantomJS的文件操作和渲染技术。
摘要由CSDN通过智能技术生成

Cameron Tink..

18

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/

另外,我想补充一点,我相信FileSystem功能仅在PhantomJS 1.3或更高版本中可用.请确保运行最新版本.我在Windows上使用了PyPhantomJS,但我确信这也可以在其他系统上顺利运行.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值