
第 1 步:创建数据库表
在 mysql 数据库中创建用户表:
create table users (
id int auto_increment primary key,
name varchar(50) not null,
surname varchar(50) not null,
email varchar(100) not null unique,
university varchar(100),
created_at timestamp default current_timestamp
);
第 2 步:创建用户模型
在您的 codeigniter 项目中,在 app/models/:
中创建一个名为 usermodel.php 的模型
<?php
namespace app\models;
use codeigniter\model;
class usermodel extends model
{
protected $table = 'users';
protected $primarykey = 'id';
protected $allowedfields = ['name', 'surname', 'email', 'university'];
protected $usetimestamps = true;
protected $createdfield = 'created_at';
}
第 3 步:安装 dompdf
在项目目录中运行以下命令来安装 dompdf:
composer require dompdf/dompdf
第 4 步:创建 pdf 生成控制器
在 app/controllers/:
中创建一个名为 pdfcontroller.php 的控制器
<?php
namespace app\controllers;
use app\models\usermodel;
use dompdf\dompdf;
use dompdf\options;
class pdfcontroller extends basecontroller
{
public function generateuserlistpdf(){
$usermodel = new usermodel();
// retrieve all users from the database
$users = $usermodel->findall();
$options = new options();
$options->set('isremoteenable',true);
$dompdf = new dompdf($options);
$html = view('user_list_pdf',['users' => $users]);
$dompdf->loadhtml($html);
$dompdf->render();
$filename = 'user_list_'.date('ymdhis').'pdf';
$dompdf->stream($filename,['attachment'=>false]);
}
}
第 5 步:为 pdf 创建 html 视图
在 app/views/ 中,创建一个名为 user_list_pdf.php 的新文件,其中包含以下内容:
<!doctype html>
<html>
<head>
<style>
table {
border-collapse: collapse;
width: 100%;
}
th, td {
border: 1px solid black;
padding: 8px;
}
th {
background-color: lightgray;
}
</style>
</head>
<body>
<h1>list of users</h1>
<table>
<tr>
<th>no</th>
<th>name and surname</th>
<th>email</th>
<th>university</th>
<th>created date</th>
</tr>
<?php foreach ($users as $index => $user) : ?>
<tr>
<td><?= $index + 1; ?></td>
<td><?= esc($user['name']); ?> <?= esc($user['surname']); ?></td>
<td><?= esc($user['email']); ?></td>
<td><?= esc($user['university']); ?></td>
<td><?= esc($user['created_at']); ?></td>
</tr>
<?php endforeach; ?>
</table>
</body>
</html>
第 6 步:定义路线
在app/config/routes.php中,添加访问pdf生成功能的路由:
$routes->get('generate-user-list-pdf', 'PdfController::generateUserListPdf');
第 7 步:测试设置
在浏览器中访问 http://yourdomain.com/generate-user-list-pdf。这应该:
从数据库中检索所有用户。
使用用户数据渲染 user_list_pdf 视图。
使用用户列表生成 pdf 并将其显示在浏览器中。
以上就是如何在 PHP CodeIgniter 中生成 Pdf sing *dompdf*的详细内容,更多请关注php中文网其它相关文章!
全网最新最细最实用WPS零基础入门到精通全套教程!带你真正掌握WPS办公! 内含Excel基础操作、函数设计、数据透视表等
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号