Laravel 5.1下载带有事件的PDF

时间:2015-09-07 12:41:27

标签: php events pdf laravel-5.1

我对Event的初始控制器代码是:

try {
            $sales = $this->sales->create([
                'customer_id'       =>  $customer->id,
                'sales_details' =>  json_encode($vData),
                'total_price'       =>  ((int)$data['q-rfh'] * (int)$data['p-rfh']) + ((int)$data['q-rfh-spro'] * (int)$data['p-rfh-spro']),
                'created_by'        =>  $user->username,
            ]);

            \Event::fire('print.invoice', $sales);

            return \Response::json([
                'type'      =>  'success',
                'message'   =>  'Success creating sales!',
            ]);
        }
        catch (\Exception $e) {
            return \Response::json([
                'type'      =>  'danger',
                'message'   =>  $e->getMessage(),
            ]);
        }

我需要使用事件打印发票,因为我需要使用ajax返回响应,以便让用户知道销售已成功完成。

事件代码就像这样简单:

public function handle(SalesModel $sales) {
        if ($sales) {
            $data = [
                'sales' =>  $sales,
            ];

            $pdf = \PDF::loadView('invoice.sales', $data);
            return $pdf->download('inv_' . Carbon::now() . '.pdf');
        }
    }

EventServiceProvider已经收听了它:

protected $listen = [
        'print.invoice' => [
            'App\Events\InvoiceEventHandler',
        ],
    ];

一切正常,但不下载PDF。我使用https://github.com/barryvdh/laravel-dompdf创建和下载PDF。有人能告诉我什么是错的吗?

1 个答案:

答案 0 :(得分:0)

我给你的想法。创建pdf文件并暂时将其存储在服务器上

// return an absolute url
$pdfFile = \PDF::create('inv_' . Carbon::now() . '.pdf');

现在在你的json响应中添加pdf文件url,以便在响应到达客户端后下载它:

return \Response::json([
    'type'      =>  'success',
    'message'   =>  'Success creating sales!',
    'pdf' => pdfFile
]);

从javascript,success()方法,您可以在其他请求中调用pdf