【问题标题】:Generate multiple PDF documents with loop使用循环生成多个 PDF 文档
【发布时间】:2018-10-04 13:34:12
【问题描述】:

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

【问题讨论】:

    标签: php laravel pdf-generation


    【解决方案1】:

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

    【讨论】:

    • 收到此错误 - Barryvdh\DomPDF\PDF 类的对象无法转换为字符串
    • 不只是创建最后一个pdf。
    • @Finchy70,我再次更新了我的代码。这次应该可以了。这是作者自己给出解决方案的Github包本身的参考链接。 Click here
    • 谢谢。只需将 loadView 更改为 loadHTML 并重组我的 pfd.blade 文件。现在效果很好。
    • 欢迎您。很高兴能帮助你。感谢您投票并接受我的回答。
    【解决方案2】:

    参考上面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');
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-14
      • 1970-01-01
      • 2023-03-18
      • 2021-12-18
      相关资源
      最近更新 更多