phantomjs是一个开源的浏览器引擎,开源渲染网页转为图片,支持js渲染~

先安装

非动态渲染(php代码版)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
全局安装
curl -sS https://getcomposer.org/installer | php
mv composer.phar /usr/local/bin/composer

替换国内镜像
composer config -g repo.packagist composer https://packagist.phpcomposer.com


composer require anam/phantommagick
composer require anam/phantomjs-linux-x86-binary


下载mac版phantomjs,
wget https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-macosx.zip
然后
cp -rf /Users/liuli/Downloads/phantomjs-2.1.1-macosx/  /Users/liuli/work/test/vendor/anam/phantomjs-linux-x86-binary/
1
2
3
4
5
6
7
8
9
运行代码
require_once "vendor/autoload.php";

	use Anam\PhantomMagick\Converter;

	$conv = new \Anam\PhantomMagick\Converter();
	$conv->source('http://baidu.com')
		->toPng()
		->save('baidu.png');

js动态渲染(shell命令版)

后来遇到需要支持js渲染的页面, 还是安装phantomjs(免安装版),下载rasterize.js,执行命令即可。

1
phantomjs rasterize.js "url" "pdf保存路径"

下边是自己用的批量的脚本

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
#/bin/bash
 
#set -v -x

. param.sh

for i in "${ar[@]}" ; do
    b=($i) #此时b就相当于二维数组里面的一维数组了,然后可以再次遍历
    uigId=${b[0]}
    uId=${b[1]}
    goodsId=${b[2]}
    money=${b[3]}
    buaId=${b[4]}

    path="pdf/${buaId}/${uigId}_${uId}.pdf"
    if [ ! -f "$path" ]; then
        echo $path
        phantomjs rasterize.js "https://*/xwm/agreement/detail/new_debt_trans_person/debt/?uid=${uId}&uigId=${uigId}&goodsId=${goodsId}&money=${money}" "${path}"
    fi
done

param.sh是个数组,如下

1
2
3
ar=('1051411927445811200 845631 -1515891827308 99949 LTJR_QY_590552323122802902'
'991177525051011378 807759 -1516186170898 56694 51_QY_590552323106029163'
'998158495453032448 915350 -1516186170925 9863 51_QY_590552323106027791')