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

PHP动态生成表格选中行导出PDF的技术方案问询

实现选中行导出PDF的服务端方案(PHP + TCPDF/mPdf)

我来帮你梳理下用PHP结合TCPDF或mPdf实现选中行导出PDF的具体步骤——这个方案确实能解决你提到的DataTables导出定制性不足、对齐混乱的问题,完全可以按需控制PDF的布局和样式。

一、前端准备:收集选中行数据

首先要确保表格里的复选框能被正确识别,建议给每行的复选框设置统一的name属性,值绑定每行的唯一标识(比如Sr.No.),方便后端精准获取选中数据:

<!-- 你的表格结构示例 -->
<table>
  <thead>
    <tr>
      <th><input type="checkbox" id="select_all"></th>
      <th>I'd</th>
      <th>Sr.No.</th>
      <th>Name</th>
      <th>Date</th>
    </tr>
  </thead>
  <tbody>
    <?php foreach($your_data_array as $row): ?>
    <tr>
      <td><input type="checkbox" name="selected_rows[]" value="<?= $row['sr_no'] ?>"></td>
      <td><?= $row['id'] ?></td>
      <td><?= $row['sr_no'] ?></td>
      <td><?= $row['name'] ?></td>
      <td><?= $row['date'] ?></td>
    </tr>
    <?php endforeach; ?>
  </tbody>
</table>
<button id="export_pdf">导出选中行到PDF</button>

然后用JS实现全选和导出提交逻辑,把选中的行ID发送到后端:

// 全选/取消全选功能
document.getElementById('select_all').addEventListener('change', function() {
  const checkboxes = document.querySelectorAll('input[name="selected_rows[]"]');
  checkboxes.forEach(cb => cb.checked = this.checked);
});

// 导出按钮点击事件
document.getElementById('export_pdf').addEventListener('click', function() {
  const selectedIds = Array.from(document.querySelectorAll('input[name="selected_rows[]"]:checked'))
    .map(cb => cb.value);
  
  if(selectedIds.length === 0) {
    alert('请至少选中一行数据');
    return;
  }

  // 用表单提交(避免AJAX下载文件的跨域/弹窗问题)
  const form = document.createElement('form');
  form.method = 'POST';
  form.action = 'export_pdf.php';
  
  selectedIds.forEach(id => {
    const input = document.createElement('input');
    input.type = 'hidden';
    input.name = 'selected_rows[]';
    input.value = id;
    form.appendChild(input);
  });
  
  document.body.appendChild(form);
  form.submit();
  document.body.removeChild(form);
});

二、后端实现:用TCPDF生成PDF

1. 安装TCPDF

如果用Composer管理依赖,执行以下命令:

composer require tecnickcom/tcpdf

如果不用Composer,直接从TCPDF官网下载源码包,放到项目目录中即可。

2. 编写导出脚本(export_pdf.php)

<?php
// 引入TCPDF(Composer安装的情况)
require_once 'vendor/autoload.php';
// 手动下载的情况替换为:require_once 'tcpdf/tcpdf.php';

// 接收前端传的选中行ID
$selectedRows = $_POST['selected_rows'] ?? [];
if(empty($selectedRows)) {
  die('没有选中任何数据');
}

// 从数据库查询选中的数据(替换成你的数据库连接逻辑)
// 示例用PDO做预处理,防止SQL注入
$pdo = new PDO('mysql:host=localhost;dbname=your_database;charset=utf8', 'your_username', 'your_password');
$placeholders = implode(',', array_fill(0, count($selectedRows), '?'));
$stmt = $pdo->prepare("SELECT id, sr_no, name, date FROM your_table WHERE sr_no IN ($placeholders)");
$stmt->execute($selectedRows);
$exportData = $stmt->fetchAll(PDO::FETCH_ASSOC);

// 创建TCPDF实例,设置页面属性
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// 设置文档元信息
$pdf->SetCreator('Your System');
$pdf->SetAuthor('Your Name');
$pdf->SetTitle('选中数据导出');

// 关闭默认页眉页脚
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);

// 设置边距和字体
$pdf->SetMargins(15, 15, 15);
$pdf->SetAutoPageBreak(true, 15);
// 如果需要支持中文,设置中文字体(比如stsongstdlight)
$pdf->SetFont('stsongstdlight', '', 12);

// 添加一页PDF
$pdf->AddPage();

// 写入标题(居中对齐)
$pdf->Cell(0, 10, '选中数据导出表', 0, 1, 'C');
$pdf->Ln(5); // 换行

// 定义表格列宽和表头
$header = ['I\'d', 'Sr.No.', 'Name', 'Date'];
$colWidths = [30, 30, 60, 40];

// 绘制表头(单元格居中)
foreach($header as $index => $title) {
  $pdf->Cell($colWidths[$index], 10, $title, 1, 0, 'C');
}
$pdf->Ln();

// 绘制表格内容
foreach($exportData as $row) {
  $pdf->Cell($colWidths[0], 10, $row['id'], 1, 0, 'C');
  $pdf->Cell($colWidths[1], 10, $row['sr_no'], 1, 0, 'C');
  $pdf->Cell($colWidths[2], 10, $row['name'], 1, 0, 'C');
  $pdf->Cell($colWidths[3], 10, $row['date'], 1, 1, 'C'); // 最后一列后换行
}

// 输出PDF:D=下载,I=在线打开,F=保存到服务器
$pdf->Output('selected_data.pdf', 'D');
?>

三、mPdf替代方案(更适合HTML布局)

如果你偏好用HTML来控制PDF样式,mPdf会更省心,它对HTML/CSS的支持比TCPDF更好:

1. 安装mPdf

composer require mpdf/mpdf

2. 编写导出脚本

<?php
require_once 'vendor/autoload.php';

$selectedRows = $_POST['selected_rows'] ?? [];
// 数据库查询部分和TCPDF示例一致...

// 创建mPdf实例
$mpdf = new \Mpdf\Mpdf();

// 用HTML构建表格(完全自定义样式)
$html = '<h1 style="text-align:center; margin-bottom:20px;">选中数据导出表</h1>';
$html .= '<table border="1" style="width:100%; text-align:center; border-collapse:collapse;">';
$html .= '<tr><th>I\'d</th><th>Sr.No.</th><th>Name</th><th>Date</th></tr>';
foreach($exportData as $row) {
  $html .= "<tr><td>{$row['id']}</td><td>{$row['sr_no']}</td><td>{$row['name']}</td><td>{$row['date']}</td></tr>";
}
$html .= '</table>';

// 写入HTML并输出PDF
$mpdf->WriteHTML($html);
$mpdf->Output('selected_data.pdf', 'D');
?>

关键注意事项

  • 数据安全:永远不要信任前端传的数据,后端必须用预处理语句查询数据库,防止SQL注入(上面的示例已经做了防护)。
  • 中文支持:TCPDF需要手动导入中文字体,而mPdf默认支持大部分中文编码,如果你有中文内容,优先选mPdf会更省事。
  • 布局定制:可以通过调整单元格宽度、字体大小、边距、CSS样式等,让PDF内容完全居中,彻底解决DataTables导出的对齐问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:05:27