https://github.com/spatie/browsershot
npm install puppeteer
こちらのコマンドでうまくいかないときは以下のコマンドでインストールします
npm install puppeteer --global
composer require spatie/browsershot
php artisan tinker
use Spatie\Browsershot\Browsershot;
$timestamp = \Carbon\Carbon::now()->format("Ymd_His_v");
$file_path = "C:/Users/hogehoge/test_puppeteer_{$timestamp}.png";
Browsershot::url('https://www.google.com/?hl=ja')->setOption('args', ['--no-sandbox','--disable-web-security'])->save($file_path);
testpuppeteer<実行日時>.png が作成されれば成功です
use Spatie\Browsershot\Browsershot;
$timestamp = \Carbon\Carbon::now()->format("Ymd_His_v");
$file_path = "C:/Users/hogehoge/test_puppeteer_{$timestamp}.png";
Browsershot::url('https://www.google.com/?hl=ja')
->setOption('args', ['--no-sandbox','--disable-web-security'])
->save( $file_path );
$file = file_get_contents( public_path( $file_path ) );
return response($file, 200)
->header('Content-Type', 'application/pdf')
->header('Content-Disposition', 'inline; filename="' . $file_path . '"');
setNodeBinary でnodeのパスを明示的に指定します
Browsershot::url('https://www.google.com/?hl=ja')
->setNodeBinary(' /home/kusanagi/.anyenv/envs/nodenv/shims/node')
use Spatie\Browsershot\Browsershot;
$html = "<h1>TEST</h1>";
Browsershot::html( $html )
->setOption('args', ['--no-sandbox','--disable-web-security'])
->save('./test.pdf');
$file = file_get_contents( public_path('./test.pdf') );
return response($file, 200)
->header('Content-Type', 'application/pdf')
->header('Content-Disposition', 'inline; filename="' . './test.pdf' . '"');
puppetter の 共有ライブラリが不足しています。
・足りない共有ライブラリを調べる
cd /YOUR-PATH-TO-PUPPETEER/puppeteer/.local-chromium/linux-818858/chrome-linux
ldd chrome
これで not found と言われている .so をインストールする必要があります。
yumコマンドでインストールしましょう。
<link rel="stylesheet" href="{{ url('/assets/css_pdf/pdfprint.css') }}">
↓ 次のようにして絶対パスに書き換えます
<link rel="stylesheet" href="{{ public_path('/assets/css_pdf/pdfprint.css') }}">
vendor/spatie/browsershot/Browsershot.php
protected function callBrowser(array $command)
{
$fullCommand = $this->getFullCommand($command);
$process = Process::fromShellCommandline($fullCommand)->setTimeout($this->timeout);
// ● この行を追加 ↓
$process->setEnv(array('LD_LIBRARY_PATH' => "/PATH/TO/YOUR/puppeteer_lib64" ));
$process->run();
こちらのパッケージを利用するともっと簡単にPDF出力することができます
composer require verumconsilium/laravel-browsershot
return \VerumConsilium\Browsershot\Facades\PDF::loadHtml('<h1>TEST印刷</h1>')
->setNodeBinary('/Users/hogehoge/.anyenv/envs/nodenv/shims/node')
->setNpmBinary('/Users/hogehoge/.anyenv/envs/nodenv/shims/npm')
->inline();