Skip to content

Pdf 门面

Pdf 门面提供一个方便的静态代理,对应 TcpdfServiceProvider 所注册的 PdfDocumentInterface 绑定。config/tcpdf-next.php 中的所有配置值都会自动应用。

php
use Yeeefang\TcpdfNext\Laravel\Facades\Pdf;

创建文件

Pdf::create() 从容器解析一个全新的 Document 实例,并预先应用所有配置默认值:

php
$pdf = Pdf::create();

$pdf->addPage()
    ->setFont('Helvetica', '', 12)
    ->cell(0, 10, '来自 Laravel 的 PDF!')
    ->save(storage_path('app/hello.pdf'));

每次调用 create() 都会返回一个新的实例。文件不会在调用之间共享。

流式 API

所有 Document 方法都可通过门面使用,并返回 static 以支持链式调用:

php
$pdf = Pdf::create()
    ->setTitle('季度报告')
    ->setAuthor('财务团队')
    ->setMargins(left: 15, top: 20, right: 15)
    ->setAutoPageBreak(enabled: true, margin: 25)
    ->addPage()
    ->setFont('Helvetica', 'B', 18)
    ->cell(0, 12, '2026 年第一季报告')
    ->ln()
    ->setFont('Helvetica', '', 11)
    ->multiCell(0, 6, $reportBody);

配置绑定

门面从 config/tcpdf-next.php 读取默认值。您可以针对个别文件覆盖任何配置:

php
// 使用配置默认值(A4 纵向、Helvetica 11pt)
$default = Pdf::create();

// 仅对此文件覆盖页面格式
$receipt = Pdf::create()
    ->setPageFormat('A5')
    ->setMargins(left: 10, top: 10, right: 10);

完整配置选项请参阅 Laravel 配置

门面类参考

php
namespace Yeeefang\TcpdfNext\Laravel\Facades;

use Illuminate\Support\Facades\Facade;

/**
 * @method static \Yeeefang\TcpdfNext\Core\Document create()
 * @method static void fake()
 * @method static void assertCreated()
 * @method static void assertCreatedCount(int $count)
 *
 * @see \Yeeefang\TcpdfNext\Core\Document
 */
class Pdf extends Facade
{
    protected static function getFacadeAccessor(): string
    {
        return \Yeeefang\TcpdfNext\Contracts\PdfDocumentInterface::class;
    }
}

使用 Pdf::fake() 进行测试

将真实绑定替换为假实现,无需生成实际 PDF 字节即可进行断言:

php
use Yeeefang\TcpdfNext\Laravel\Facades\Pdf;

public function test_invoice_generates_pdf(): void
{
    Pdf::fake();

    $response = $this->get('/invoices/42/pdf');

    $response->assertOk();

    // 断言文件已被创建
    Pdf::assertCreated();

    // 断言恰好创建了一份文件
    Pdf::assertCreatedCount(1);
}

检查假文件

假实现会记录每个方法调用,让您验证流式链的内容:

php
Pdf::fake();

$this->get('/invoices/42/pdf');

Pdf::assertCreated(function ($pdf) {
    return $pdf->getTitle() === '发票 #42'
        && $pdf->getPageCount() >= 1;
});

在测试中替换绑定

若整合测试需要真实的 PDF 输出,可绑定自定义实现:

php
use Yeeefang\TcpdfNext\Contracts\PdfDocumentInterface;
use Yeeefang\TcpdfNext\Core\Document;

$this->app->bind(PdfDocumentInterface::class, function () {
    return Document::create()->setCompression(false);
});

下一步

以 LGPL-3.0-or-later 许可证发布。