php - 使用循环生成多个PDF文档

标签 php laravel pdf-generation

这是我的 Laravel Controller 之一中的一些代码,用于生成多个时间表 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');
        }
    }

最佳答案

首先将所有 View 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`.
}

关于php - 使用循环生成多个PDF文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49999146/

相关文章:

javascript - 表单提交按钮不起作用

php - 从 Laravel 5.1 中的通用数据库查询获取 Eloquent 模型的实例

c# - 如何将 Silverlight 数据网格转换为 PDF?

pdf-generation - 使用 Zend Framework 2 生成 PDF 文件

php - 使用 update_batch 增加数据库中的字段 自动添加单引号

php - 在动态页面上使用 PHP while 循环不起作用

javascript - 如何在 Laravel 中将变量从脚本传递到 Controller

php - 如何在我的 Laravel 包中包含 bootstrap 和 jquery

python - python-pptx 是否支持将文件保存为 pdf?

javascript - 如果某个 div 具有 css 值,则显示其他 div