使用循环生成多个PDF文档

时间:2018-04-24 10:17:35

标签: php laravel pdf-generation

以下是我的一个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');
        }
    }

3 个答案:

答案 0 :(得分:2)

首先在一个变量中获取所有视图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`.
}

答案 1 :(得分:0)

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');
        $sheet->download($hours->user->name.' - '.$week_ending.'.pdf');
    }
}

我同意,return语句终止执行。尝试删除return语句。检查上面的代码。

答案 2 :(得分:0)

请参考Himashu的上述答案。我想添加一些可以在特定位置下载多个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');
    }