循环生成多个PDF文档

Generate multiple PDF documents with loop

这是我的一个 Laravel 控制器中的一些代码,用于生成多个时间表 PDF。它只创建 1,我确定它是由于 return 语句,但我如何让它创建所有 PDF?我正在使用 barryvdh/laravel-dompdf.

public function alltimesheets(Request $request)
    {
        $weeks = Timesheet::where('week_ending', $request->week_ending)->get();
        $week_ending = Carbon::parse($request->week_ending)->format('d-m-Y');
        foreach($weeks as $hours)
        {

            $pdf = PDF::loadView('pdf.timesheet', compact('hours', 'week_ending'));
            $sheet = $pdf->setPaper('a4', 'landscape');
            return $sheet->download($hours->user->name.' - '.$week_ending.'.pdf');
        }
    }

首先将所有视图 html 放在一个变量中,然后将其传递给 PDF。

试试下面的代码:

public function alltimesheets(Request $request)
{
    $weeks = Timesheet::where('week_ending', $request->week_ending)->get();
    $week_ending = Carbon::parse($request->week_ending)->format('d-m-Y');
    $html = '';
    foreach($weeks as $hours)
    {
        $view = view('pdf.timesheet')->with(compact('hours', 'week_ending'));
        $html .= $view->render();
    }
    $pdf = PDF::loadHTML($html);            
    $sheet = $pdf->setPaper('a4', 'landscape');
    return $sheet->download('download.pdf');  // $hours can not be accessed outside foreach. So changed the file name to `download.pdf`.
}

参考上面的回答。我想添加一些代码,可以在特定位置下载多个 pdf。这会为每个文件创建一个单独的 pdf。

$invoices = Invoices::where('user_id', '=', $user_id)->get();

    foreach($invoices as $key => $invoice)
    {
        $user_details = Users::where('id',$invoice->user_id)->first();
        $html = '';
        $view = view('pdf.invoice_compact')->with(compact('user_details','invoice'));
        $html .= $view->render();
        PDF::loadHTML($html)->save(public_path().'/bulk_invoices/'.$invoice->id.'.pdf');
    }