laravel框架中将数据导出为PDF文件功能流程步骤
在laravel中,您可以借助这个名为 dompdf 的有用软件包轻松地将数据导出为pdf格式。
dompdf扩展包:
https ://github.com/barryvdh/laravel-dompdf
我通过将用户数据从数据库导出到 pdf 文件为您提供了一个示例。
进入步骤
1.首先安装和配置 dompdf 包
composer require barryvdh/laravel-dompdf
php artisan vendor:publish --provider="Barryvdh\DomPDF\ServiceProvider"
2.将此功能添加到您的控制器以查看 pdf
public function viewPDF()
{
$users = User::all();
$pdf = PDF::loadView('pdf.usersdetails', array('users' => $users))
->setPaper('a4', 'portrait');
return $pdf->stream();
}
将此功能添加到您的控制器中以下载 pdf...
public function downloadPDF()
{
$users = User::all();
$pdf = PDF::loadView('pdf.usersdetails', array('users' => $users))
->setPaper('a4', 'portrait');
return $pdf->download('users-details.pdf');
}
功能路由:
Route::post('users/view-pdf', [HomeController::class, 'viewPDF'])->name('view-pdf');
Route::post('users/download-pdf', [HomeController::class, 'downloadPDF'])->name('download-pdf');
视图:
使用任何 html 模板来导出数据
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Details</title>
<style>
table {
width: 95%;
border-collapse: collapse;
margin: 50px auto;
}
/* Zebra striping */
tr:nth-of-type(odd) {
background: #eee;
}
th {
background: #3498db;
color: white;
font-weight: bold;
}
td,
th {
padding: 10px;
border: 1px solid #ccc;
text-align: left;
font-size: 18px;
}
</style>
</head>
<body>
<div style="width: 95%; margin: 0 auto;">
<div style="width: 10%; float:left; margin-right: 20px;">
<img src="{{ public_path('assets/images/logo.png') }}" width="100%" alt="">
</div>
<div style="width: 50%; float: left;">
<h1>All User Details</h1>
</div>
</div>
<table style="position: relative; top: 50px;">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Date Of Joining</th>
</tr>
</thead>
<tbody>
@foreach ($users as $user)
<tr>
<td data-column="First Name">{{ $user->first_name }}</td>
<td data-column="Last Name">{{ $user->last_name }}</td>
<td data-column="Email" style="color: dodgerblue;">
{{ $user->email }}
</td>
<td data-column="Date">
{{ date('F j, Y', strtotime($user->create_at)) }}
</td>
</tr>
@endforeach
</tbody>
</table>
</body>
</html>
相关文章