abcreche / print
生成打印文档
v3.0.0
2024-09-03 07:32 UTC
Requires
- php: >=8.2
- dompdf/dompdf: ^3.0.0
- laravel/framework: >=11
- spatie/browsershot: ^4.3
Requires (Dev)
- mockery/mockery: ^1.5
- orchestra/testbench: ^6.17.0
- phpunit/phpunit: ^11.0
This package is auto-updated.
Last update: 2024-09-03 07:32:47 UTC
README
安装
您可以使用以下命令通过composer安装此包:
composer require abcreche/print
此包将自动注册自身
用法
此包使用“打印文档模板”类来生成PDF,您可以通过浏览器打印它。这些类填充了您按喜好定位的数据。这对于填写依赖于特定模板的官方文件特别有帮助。
创建打印模板
首先,创建一个新的打印文档
php artisan make:print ReceiptTemplate
该文件位于 app/PrintTemplates
.
├── app
│ ├── PrintTemplates
│ │ ├── ReceiptTemplate.php
│
└── composer.json
现在您可以在控制器中为此打印模板生成PDF
<?php namespace App\Http\Controllers; use App\Receipt; use ABCreche\Printer\Facades\Printer; use App\PrintTemplates\ReceiptTemplate; class ReceiptController extends Controller { public function print(Receipt $receipt) { return Printer::download(new ReceiptTemplate($receipt), 'receipt.pdf'); } }
配置打印模板
这是打印模板的默认外观
<?php namespace App\PrintTemplates; use App\Receipt; use ABCreche\Printer\Printer; class ReceiptTemplate implements PrintTemplate { public function build() { $this->firstPage()->write('Hello There'); } }
管理页面和内容
您要在文档中添加的每个内容都需要与一个页面关联。
由于我们处理的是打印文档,因此将元素定位在特定页面中非常重要。
您可以通过这种方式添加新页面
public function build() { $this->addPage(); }
然后您将在您最后添加的页面上添加内容。
public function build() { $this->lastPage()->write('I will appear on the first page'); $this->addPage(); $this->lastPage()->write('I will appear on the second page'); }
写入数据
让我们在文档上写一些数据
public function build() { $this->lastPage() ->write($receipt->number) ->top('10px') ->left('100px'); $this->lastPage() ->write($receipt->total) ->bottom('35px') ->right('50%'); return $this; }
您也可以链式调用方法
public function build() { // Orders of direction is the same as in CSS for padding / margin properties return $this->lastPage() ->write($receipt->number, '10px', null, null, '100px') ->write($receipt->total, null, '35px', '50%', null); }
方向
您可以通过设置方向属性来选择文档的方向。
// Default: portrait // Options: 'portrait', 'landscape' protected $orientation = 'portrait';
页面边距
您可以设置页面边距。
// Default: 25mm protected $pageMargin = '25mm';
预览
您可以通过从控制器返回它来预览任何PrintTemplate。
Route::get('printer', function () { $receipt = App\Receipt::find(1); return new App\PrintTemplates\ReceiptTemplate($receipt); });
然后您可以使用Chrome开发者工具渲染页面的打印版本
图片来自 这篇Stackoverflow帖子
然后切换开发者工具到设备渲染,并将页面尺寸设置为
- A4 : 595 x 842
使用这样的预览将帮助您构建模板。当将它们转换为PDF时,它们将正好与预览一样。
待办事项
支持