类似Laravel的Mail包的文档打印

0.2.1 2019-11-25 11:53 UTC

This package is auto-updated.

Last update: 2024-09-07 20:55:53 UTC


README

介绍

Printer提供了一个使用类似Laravel的Mailable的API来渲染PDF的方法。

安装

$ composer require iamproperty/print

编写可打印的内容

所有可打印类的配置都是在build方法中完成的。在这个方法中,你可以调用viewwith方法来配置要打印的视图。

配置视图

在一个可打印类的build方法中,你可以使用view方法来指定在渲染文档内容时应使用哪个模板。由于每个文档通常使用一个Blade模板来渲染其内容,因此你在构建文档的HTML时拥有Blade模板引擎的全部功能和便利性。

/**
 * Build the document.
 *
 * @return $this
 */
public function build()
{
    return $this->view('printed.orders.invoice');
}

视图数据

通过公共属性

通常,你可能希望将一些数据传递给你的视图,以便在渲染文档的HTML时使用。你可以通过两种方式使数据可供视图使用。首先,你可以在你的可打印类中定义任何公共属性,这些属性将自动提供给视图。例如,你可以将数据传递到你的可打印类的构造函数中,并将这些数据设置到类上定义的公共属性中。

<?php

namespace App\Printed;

use App\Order;
use IAMProperty\Printer\Printable;

class OrderShipped extends Printable
{
    /**
     * The order instance.
     *
     * @var Order
     */
    public $order;

    /**
     * Create a new printable instance.
     *
     * @return void
     */
    public function __construct(Order $order)
    {
        $this->order = $order;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->view('printed.orders.shipped');
    }
}

一旦数据被设置到公共属性中,它将自动在视图中可用,因此你可以像访问Blade模板中的其他任何数据一样访问它。

<div>
    Price: {{ $order->price }}
</div>

通过with方法

如果你想在数据发送到模板之前自定义文档数据的格式,你可以通过with方法手动将数据传递给视图。通常,你仍然会通过可打印类的构造函数传递数据;然而,你应该将此数据设置为protectedprivate属性,以便数据不会自动提供给模板。然后,当调用with方法时,传递一个包含你希望提供给模板的数据的数组。

<?php

namespace App\Printed;

use App\Order;
use IAMProperty\Printer\Printable;

class OrderShipped extends Printable
{
    /**
     * The order instance.
     *
     * @var Order
     */
    protected $order;

    /**
     * Create a new printable instance.
     *
     * @return void
     */
    public function __construct(Order $order)
    {
        $this->order = $order;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->view('printed.orders.shipped')
                    ->with([
                        'orderName' => $this->order->name,
                        'orderPrice' => $this->order->price,
                    ]);
    }
}

一旦数据被传递给with方法,它将自动在视图中可用,因此你可以像访问Blade模板中的其他任何数据一样访问它。

<div>
    Price: {{ $orderPrice }}
</div>

渲染可打印的内容

有时你可能希望在不需要将其转换为PDF的情况下捕获可打印内容的HTML内容。为此,你可以调用可打印的toHtml方法。此方法将返回可打印的评估内容的字符串。

$invoice = App\Invoice::find(1);

return (new App\Printed\InvoicePaid($invoice))->toHtml();

在浏览器中预览可打印的内容

在设计可打印的模板时,在浏览器中快速预览渲染的可打印内容,就像典型的Blade模板一样,是很方便的。为此,你可以在路由闭包或控制器中直接返回任何可打印的内容。当返回可打印的内容时,它将被渲染并在浏览器中显示,这样你就可以快速预览其设计,而无需打开单独的PDF文件。

Route::get('printable', function () {
    $invoice = App\Invoice::find(1);

    return new App\Printed\InvoicePaid($invoice);
});

还可以使用Printer外观来渲染可打印的模板,而不渲染文档。

Route::get('printable', function () {
    $invoice = App\Invoice::find(1);

    return Printer::render(new App\Printed\InvoicePaid($invoice));
});