带循环生成多个PDF文档 [英] Generate multiple PDF documents with loop

查看:47
本文介绍了带循环生成多个PDF文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Here is some code in one of my Laravel controllers to generate multiple timesheet PDF's. It only creates 1 and Im sure its due to the return statement but how do i get it to create all PDF's? I'm using 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.

First get all views html in one variable and then pass it to 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文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆