You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用DataTables搜索筛选数据后如何通过FPDF导出对应结果为PDF

实现方案

步骤1:前端页面添加导出按钮与数据传递逻辑

先完成DataTables初始化,添加自定义导出按钮,点击时直接获取当前搜索筛选后的所有行数据,提交给FPDF生成接口即可。代码如下:

// 初始化DataTables
const table = $('#table').DataTable({
    // 你原有Datatables的其他配置(分页、语言配置等保留即可)
    dom: 'Bfrtip', // 开启按钮容器
    buttons: [
        {
            text: '导出筛选结果为PDF',
            action: function () {
                // 仅获取当前搜索筛选生效后的所有行数据
                const filteredData = table.rows({ search: 'applied' }).data().toArray();
                // 创建临时表单提交数据到FPDF接口
                const form = document.createElement('form');
                form.method = 'POST';
                form.action = '你的FPDF接口地址,比如generate_pdf.php';
                form.target = '_blank'; // 新窗口打开生成的PDF
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = 'filtered_patients';
                input.value = JSON.stringify(filteredData);
                form.appendChild(input);
                document.body.appendChild(form);
                form.submit();
                document.body.removeChild(form);
            }
        }
    ]
});

步骤2:修改FPDF生成接口代码

原有代码是直接查询全量数据库数据,修改为接收前端传递的筛选后患者数组,直接循环渲染PDF即可:

<?php
require "fpdf/fpdf.php";
include "db.php";
include "patients-class.php";
$db= new Database();
$conn = $db->getConnection();
$patient_obj= new patient($conn);

// 接收前端传的筛选后患者数据
$filteredPatients = json_decode($_POST['filtered_patients'], true);

$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont("Arial","B",16);
$pdf->SetTextColor(252,3,3);
$pdf->cell(200,20,"patients information","0","1","C");
// 表格表头
$pdf->SetTextColor(0,0,0);
$pdf->Cell(15,10,"NO","1","0","C");
$pdf->Cell(30,10,"Name","1","0","C");
$pdf->Cell(55,10,"Email","1","0","C");
$pdf->Cell(30,10,"Phone ","1","0","C");
$pdf->Cell(30,10,"Birth Date","1","0","C");
$pdf->Cell(30,10,"Gander","1","1","C");

$i=0;
// 循环筛选后的数据生成内容,不再查询全量数据库
foreach($filteredPatients as $row){
    $i++;
    extract($row);
    $pdf->SetFont("Arial","",11);
    $pdf->Cell(15,10,$i,"1","0","C");
    $pdf->Cell(30,10,$patientFName." ".$patientLName,"1","0","C");
    $pdf->Cell(55,10,$email,"1","0","C");
    $pdf->Cell(30,10,$phoneNumber,"1","0","C");
    $pdf->Cell(30,10,$birthDate,"1","0","C");
    $pdf->Cell(30,10,$gander,"1","1","C");
    $pdf->SetFont("Arial","",14);
}
$pdf->Output();
?>

注意事项

  • 你当前的表格代码里没有渲染Email字段,DataTables获取的行数据会缺少Email值,可以在表格tbody里加一个隐藏的<td>存放Email,或者在DataTables初始化时通过ajax拉取数据时带上Email字段即可。
  • 如果担心前端传递数据被篡改,也可以替换逻辑为传递Datatables的搜索关键词给后端,后端根据关键词做模糊查询后再生成PDF,整体流程和上述方案一致。

内容的提问来源于stack exchange,提问作者oliver

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 03:54:01