问题描述
我正在使用barryvdh / laravel-dompdf生成pdf。
我正在尝试从数据收集中生成一个包含多页的pdf文件,问题是我只能得到第一个元素和一页。使用foreach循环生成页面。另外,我试图在刀片中使用foreach,但随后我只得到最后一页。
Controller:
public function multiplePagesPdf(Request $request)
{
$kuponai = Kuponas::all();
//dd($kuponas);
$html = '';
foreach($kuponai as $kuponas)
{
$view = view('pdf.multiple')->with(compact('kuponas'));
$html .= $view->render();
}
$pdf = PDF::loadHTML($html);
$sheet = $pdf->setPaper('a4','landscape');
return $sheet->stream('sugeneruoti.pdf');
}
我的刀片文件中可能有问题:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1.0" />
<title>Dovanų kuponas</title>
</head>
<body>
<div class="coupon">
<div class="page">
<div class="subpage">
<div class="container" style="
width: 21cm;
height: 16cm;
position: absolute;
top: 6.8cm;
font-family: DejaVu Sans;
background: white;
">
<h2>{{!! $kuponas->kupono_nr !!}}</h2>
<h3 style="margin-left: 3.2cm">
Dovanų kupono numeris:
<span style="color: black"></span>
</h3>
</div>
</div>
</div>
</div>
</body>
</html>
<style>
@page {
size: A4;
margin: 0;
}
@media print {
.page {
margin: 0;
border: initial;
border-radius: initial;
width: initial;
min-height: initial;
box-shadow: initial;
background: initial;
page-break-after: always;
}
}
</style>
解决方法
您提供的代码段中有某些地方是错误的,我将首先解释这些错误,然后再提供正确的方法(为此我得到结果)。
- 首先
您已经与&compact一起使用,我不知道它是否能获得正确的结果,但是您应该使用其中任何一种还是使用view方法的数组语法。
- 第二
您正在执行的操作是将视图呈现为html,然后将其隐藏,因此,您的html看起来就像
<html>
.... content
</html>
<html>
.... content
</html>
& so on.
- 第三次
由于您添加的嵌入式CSS,您的CSS混乱了,无法正常工作。
解决方案
我本可以使用View Components创建具有不同数据的相似视图。 因此,我们将在resources / views / components / single.blade.php中创建一个组件(在这里我将其命名为single)。 从您的角度来看,我已经在单个组件中添加了重复代码。现在,您的优惠券div类在单个组件中。
<div class="coupon">
<div class="page">
<div class="subpage">
<div>
<h2>{{ $kuponas->kupono_nr }}</h2>
<h3>
Dovanų kupono numeris:
<span></span>
</h3>
</div>
</div>
</div>
</div>
然后在您看来
<!DOCTYPE html>
<html lang="en">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<head>
<title>Dovanų kuponas</title>
<style>
.page-break {
page-break-after: always;
}
</style>
</head>
<body>
@php $count = 0;@endphp
@foreach ($kuponai as $kuponas)
@php $count++ @endphp
<div class="container {{ (count($kuponai)-1 >= $count) ? 'page-break' : '' }}">
@component('pdf.components.single',['kuponas' => $kuponas])
@endcomponent
</div>
@endforeach
</body>
</html>
使用分页符类来创建分页符,我已经使用count条件删除了一个额外的分页符。我正在将kuponas的数据传递给组件。
最后更改您的控制器,
public function multiplePagesPdf(Request $request)
{
$kuponai = Kuponas::all();
//dd($kuponas);
$view = view('pdf.multiple',['kuponai' => $kuponai]);
$html = $view->render();
$pdf = PDF::loadHTML($html)->setPaper('a4','landscape');
return $pdf->stream('sugeneruoti.pdf');
}