php使用phantomjs生成pdf
phantomjs是一款可以用于后台渲染html,包括执行js,和引用css样式,可以用于爬取网页,也可以生成pdf,支持linux,windows,mac平台.
mac平台
- mac平台使用brew install phantomjs
linux平台
- centos 上使用yum -y install fontconfig,安装依赖环境,
- 解压tar xjf /tmp/phantomjs-2.1.1-linux-i686.tar.bz2 -C /usr/local/
- 重命名mv /usr/local/phantomjs-2.1.1-linux-i686 /usr/local/phantomjs
- 建立软链接 ln -s /usr/local/phantomjs/bin/phantomjs /usr/bin/
安装完成后使用phantomjs -v测试下,当前最新版是2.1.1
php-phantomjs是一个php对phantomjs进行二次包装的库,使用它可以更方便的用php执行phantomjs,我们使用composer安装,我的composer.json如下
{
"name": "np-power/pdf",
"description": "get pdf pages through PhantomJS",
"keywords": ["PhantomJS", "Testing", "Headless Browser"],
"authors": [
{
"name": "huangtao"
}
],
"require": {
"php": ">=5.3.0",
"jonnyw/php-phantomjs": "^4.6"
},
"require-dev": {
},
"autoload": {
},
"config": {
"bin-dir": "/usr/local/bin"
},
"scripts": {
"post-install-cmd": [
"PhantomInstaller\\Installer::installPhantomJS"
],
"post-update-cmd": [
"PhantomInstaller\\Installer::installPhantomJS"
]
},
"repositories": {
"packagist": {
"type": "composer",
"url": "https://packagist.phpcomposer.com"
}
}
}
需要注意的是有一个config下bin-dir,是指向phantomjs的执行目录,
script下PhantomInstaller是一个phantomjs安装工具,如果bin-dir指定且已经安装好phantomjs,PhantomInstaller安装会跳过,这种方式安装太慢,所以建议前面的方式.
repositories -> packagist是一个国内的composer,可以帮助你加快加载composer插件速度.
下面开始测试一次,以百度为例子
<?php
require 'vendor/autoload.php';
use JonnyW\PhantomJs\Client;
$client = Client::getInstance();
$client->getEngine()->setPath('/usr/local/bin/phantomjs');
/**
* @see JonnyW\PhantomJs\Http\Request
* 不能使用百度的http,百度自动跳转到https会导致生成pdf失败
**/
$request = $client->getMessageFactory()->createPdfRequest('https://www.baidu.com', 'GET');
$request->setOutputFile('./caches/document.pdf');
$request->setFormat('A4');
$request->setOrientation('landscape');
$request->setMargin('1cm');
/**
* @see JonnyW\PhantomJs\Http\Response
**/
$response = $client->getMessageFactory()->createResponse();
// Send the request
$client->send($request, $response);
header('location:caches/document.pdf');
现在caches下有个document.pdf就是生成的pdf