Php 使用循环生成多个PDF文档
下面是我的一个Laravel控制器中生成多个时间表PDF的一些代码。它只创建1,我确定这是由于return语句造成的,但是我如何让它创建所有PDF?我使用的是barryvdh/laravel dompdfPhp 使用循环生成多个PDF文档,php,laravel,pdf-generation,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();
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');
}
获取此错误-Barryvdh\DomPDF\PDF类的对象无法转换为stringNo仅创建最后一个PDF。@Finchy70,我已再次更新代码。这一次应该有效。这里是Github包本身的参考链接,作者自己在这里给出了解决方案。谢谢只需将loadView更改为loadHTML并重新构造我的pfd.blade文件。很好,欢迎光临。很乐意帮忙。谢谢你投票并接受我的回答。