Laravel-snappy导出PDF

Laravel框架
533
0
0
2022-11-07

参考文章:

PDF 扩展包使用

使用Laravel-snappy导出PDF

wkhtmltopdf/laravel-snappy 不呈现页眉和页脚

Snappy & wkhtmltopdf:页脚中的页码

使用 Laravel snappy 生成 PDF 并集成到 Laravel-admin

使用

  1. 安装 https://wkhtmltopdf.org/downloads.html
 32位:
 $ composer require h4cc / wkhtmltopdf-i386 0.12.x
 $ composer require h4cc / wkhtmltoimage-i386 0.12.x,
 64位:
 $ composer require h4cc/wkhtmltopdf-amd64 0.12.x
 $ composer require h4cc/wkhtmltoimage-amd64 0.12.x

 (uname -a 命令查看系统位数)

 cp vendor/h4cc/wkhtmltoimage-amd64/bin/wkhtmltoimage-amd64 /usr/local/bin/
 cp vendor/h4cc/wkhtmltopdf-amd64/bin/wkhtmltopdf-amd64 /usr/local/bin/
 并使其可执行:
 chmod +x /usr/local/bin/wkhtmltoimage-amd64 
 chmod +x /usr/local/bin/wkhtmltopdf-amd64
  1. 安装 snappy 包
composer require barryvdh/laravel-snappy
  1. 配置
  2. 将 ServiceProvider 添加到 config /app.php 中的 providers 数组中
Barryvdh\Snappy\ServiceProvider::class,
或添加到 Facade 中
'PDF' => Barryvdh\Snappy\Facades\SnappyPdf::class,
'SnappyImage' => Barryvdh\Snappy\Facades\SnappyImage::class,
  1. 生成配置文件
php artisan vendor:publish --provider="Barryvdh\Snappy\ServiceProvider"
  1. 注意点
cd /usr/local/bin/
ls
  1. Laravel-snappy导出PDF
  2. Laravel-snappy导出PDF
  3. 使用
  • PDF
  下载
  $pdf = \PDF::loadView('welcome', $data);
  return $pdf->download('welcome.pdf');

  渲染页面
  $html = '<html><head><meta charset="utf-8"></head><h1>订单id</h1><h2>12346546</h2></html>';
  $pdf = \PDF::loadHTML($html);
  return $pdf->inline();

  通过外部链接生成
  return PDF::loadFile('http://www.github.com')->inline('github.pdf');

- Image
```php
    一:
    下载
    $img = \SnappyImage::loadView('welcome', $data);
    return $img->download('welcome.png');

    二:
    渲染页面
    $html = '<html><head><meta charset="utf-8"></head><h1>订单id</h1><h2>12346546</h2></html>';
    $img = \SnappyImage::loadHTML($html);
    return $img->inline();

Laravel-snappy导出PDF

  1. 通过外部链接生成
  2. 页眉、页脚、页码
#header
 <!DOCTYPE html> 
 <html lang="en"> 
 <head> 
 </head> 
 <body> 
 <div style="background: blanchedAlmond;color:green;">My Header is amazing<div> 
 </body> 
 </html>
#footer
 <!DOCTYPE html> 
 <html lang="en"> 
 <head> 
 </head> 
 <body> 
 <div style="background: blanchedalmond; color:green;">Copyright &copy; 2020</div> 
 </body> 
 </html>
     $data = [
         'name' => '测试pdf'
     ];
     $header = \view('header')->render();
     $footer = \view('footer')->render();
     $pdf = \PDF::loadView('pdf', $data)
         ->setOption('margin-top', '20mm')
         ->setOption('margin-bottom', '20mm')
         ->setOption('minimum-font-size', 25)
         ->setOption('header-html', $header)
         ->setOption('footer-html', $footer)
         ->setOption('footer-right', '页面 [page]')
         ->setOption('footer-font-size', 8)
         ->setOption('footer-spacing', 5);
     return $pdf->download('pdf.pdf');
  1. 中文乱码解决
cd /usr/share/fonts
ls

  1. alt="Laravel-snappy导出PDF" />
  2. PDF 分页问题
  3. 使用 css 的 page-break-after:alwayspage-break-inside:aovid

有没有其他坑补充的~~