一、下载 wkhtmltopdf
网址 https://wkhtmltopdf.org/
这里注意选择和自己服务器版本匹配的包
我的服务器是 ubunutu 16.04 64位 getconf LONG_BIT #查看位数
所以下载 Ubuntu 16.04 (xenial) amd64
二、安装依赖
install libXrender* install libssl*
三、安装 laravel-snappy 扩展包
composer require barryvdh/laravel-snappy
将ServiceProvider添加到config / app.php中的providers数组
Barryvdh\Snappy\ServiceProvider::class,
添加facade到config / app.php中的aliases数组中
'PDF' => Barryvdh\Snappy\Facades\SnappyPdf::class,
'SnappyImage' => Barryvdh\Snappy\Facades\SnappyImage::class,
生成配置文件
php artisan vendor:publish
选择 2 这个时候 就在 config/snappy.php
具体配置如下
binary 这是执行文件,配置文件可以自行执行,一般是通过composer安装的,则默认会在 vendor包下面
'pdf' => [ 'enabled' => true, 'binary' => '/usr/local/bin/wkhtmltopdf-amd64', 'timeout' => false, 'options' => [], 'env' => [], ], 'image' => [ 'enabled' => true, 'binary' => '/usr/local/bin/wkhtmltoimage-amd64', 'timeout' => false, 'options' => [], 'env' => [], ],
/usr/local/bin/ 查看目录
四、踩坑
中文字体问题
如果 windows 里的字体文件有 C:\Windows\Fonts\simsun.ttc ,直接上传到服务器里的 /usr/share/fonts 里
宋体或其他中文字体添加到 /usr/share/fonts/ 里
如果没有 simsun.ttc 这个字体文件,下载一个上传
这里需要特别说明一下,不能直接去使用file文件,生成的中文汉字会是乱码。
需要通过http方式去 loadFile 这种方式去生成,可解决中文乱码问题
关于 Js 不生效问题
我需要转成 pdf 的页面有大量的 echarts 图表, 有大量的 js 控制,开始一个图表都没有显示,然后断点测试法,发现我 js 里有一段代码是用的 let 声明的变量,改成 var 就好了。
所以,wkhtmltopdf 不支持 ecs6
PDF 分页问题
使用 css 的 page-break-after:always; 或 page-break-inside:aovid;
五、运行效果
1、代码
class ATest extends TestCase { public function testTwo(){ //$pdf = app(Barryvdh\Snappy\ServiceProvider::class); //dump($pdf); //$pdf = app('snappy.pdf'); //$result = \Barryvdh\Snappy\Facades\SnappyPdf::loadFile(__DIR__.'/a.html')->save(__DIR__.'/file.pdf'); $content = file_get_contents('http://www.baidu.com/a.html'); //$result = \Barryvdh\Snappy\Facades\SnappyImage::loadFile(__DIR__.'/a.html')->save('/tmp/file.jpg'); //$result = \Barryvdh\Snappy\Facades\SnappyImage::loadHtml($content)->save('/tmp/file.jpg'); $result = \SnappyImage::loadFile('http://www.baidu.com/a.html')->setOption('height','1000')->save('/tmp/file.jpg'); dump($result); $this->assertIsBool(true); } }
加载远程文件,需要使用loadFile 这个方法去请求
a.html
<html> <head> <style> @font-face { font-family: 'msyh'; font-style: normal; font-weight: normal; src: ('/usr/share/fonts/truetype/msyh.ttc') format('truetype'); } body { font-family: msyh, DejaVu Sans,sans-serif; } </style> </head> <body> <h1 style="color:red">123</h1> <p>最近产品有新需求生成 pdf,我第一反应就是 laravel-snappy 咯。<br> laravel-snappy 的优点不多说,这篇主要是踩坑记录。 </p> <img src="http://www.xiaosongit.com/Public/Upload/image/20200228/1582905140915430.png"> <h2>中国人</h2> echo 111 </body> <html>
以上的代码,就是将上面html文件生成为图片。
2、运行代码
./vendor/bin/phpunit tests/Feature/ATest
3、查看效果
a.html 运行效果
生成图片的效果:
生成pdf看看:
到此结束
推荐一个比较另外一个比较好的pdf类库 mikehaertl/phpwkhtmltopdf