HTML页面生成图片

14 篇文章 0 订阅
3 篇文章 0 订阅

1、使用工具:phantomjs(点击了解)

2、js脚本内容(保存为index.js):

try{
   var system = require('system');
   console.log(system.args);
   if (system.args.length == 1) {
      throw '请输入参数-url=URL -path=SAVEPATH';
   }
   
   var args = new Array();
   system.args.forEach(function(item, index){
      console.log(item, index);
      if (index > 0) {
         item = item.split('=');
         console.log(item);
         args[item[0]] = item[1];
      }
   });


   var page = require('webpage').create(); 
   var address = args['url']; //填写需要打印的文件位置
   var output = args['path']; //存储文件路径和名称
   page.viewportSize = { width: 800, height: 600 };//设置长宽
   console.log(address, output);
   page.open(address, function (status) {
      if (status !== 'success') {
         console.log('Unable to load the address!');
         phantom.exit();
      } else {
         //window.setTimeout(function () {
            page.render(output);
            console.log(page.render(output))
            phantom.exit();
         //}, 500);
      }
   });
}catch(e){
   console.log(e);
   phantom.exit();
}

3、直接运行指令,生成图片

phantomjs E:\wens\HtmlToImage\js\index.js url=http://baidu.com path=E:/wens/img.png

指令分析:

phantomjs:工具指令,(提示:安装完phantomjs,需要将phantomjs添加到系统的环境变量中

E:\wens\HtmlToImage\js\index.js:html生成image的脚本

url=http://baidu.com:需要生成图片的页面路由

path=E:/wens/img.png:图片保存路径

4、php运行指令,生成图片

$command = "phantomjs E:\wens\HtmlToImage\js\index.js url=http://baidu.com path=E:/wens/img.png";

exec($command . " 2>&1", $output, $return_var);

var_dump($output, $return_var);

(提示:指令后面拼接 “2>&1”是为了将exec运行失败的原因输出到$output中)

5、补充exec输出错误信息(摘自:https://www.cnblogs.com/carolina/p/5640591.html

原型:

string exec( string $command [, array &$output [, int &$return_var]])

功能:

exec()执行command参数所指定的命令。

参数:

command:

要执行的命令

output:

如果提供了output参数,那么会用命令执行的输出流(stdout)填充此数组,每行输出填充数组中的一个元素。数组中的数据不包含行尾的空白字符,例如\n字符。请注意,如果数组中已经包含了部分元素,exec()函数会在数组末尾追加内容。如果你不想在数组末尾进行追加,请在传入exec()函数之前对数组使用unset()函数进行重置。

return_var

如果同时提供output和return_var参数,命令执行后的返回状态会被写入到此变量。

在bash中0,1,2三个数字分代表STDIN_FILENO、STDOUT_FILENO、STDERR_FILENO,即标准输入(一般是键盘),标准输出(一般是显示屏,准确的说是用户终端控制台),标准错误(出错信息输出)

0:标准输入 STDIN_FILENO

1:标准输出 STDOUT_FILENO

2:标准错误 STDERR_FILENO

将2和重定向到1可以使用:2>&1

exec(command+'" 2>&1",$res);

print_r($res);//这样就可以看到标准错误流的内容了

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值