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

PHP库存管理系统添加表格打印与导出PDF功能实现咨询

PHP库存管理系统打印/导出PDF实现方案

一、表格打印功能实现(无需额外依赖,适合新手)

  • 第一步:在报表页面(即$page对应的php文件,如home.php)表格上方添加按钮
<button id="printBtn" class="btn btn-primary">打印报表</button>
  • 第二步:添加打印专用样式,在你现有代码的<style>标签内插入以下代码
@media print {
  /* 隐藏不需要打印的页面元素 */
  #topbar, .navbar, .back-to-top, .modal, #printBtn, #exportPdfBtn {
    display: none !important;
  }
  /* 适配打印样式 */
  body {
    background: #fff !important;
  }
  #view-panel {
    width: 100% !important;
    margin: 0 !important;
    padding: 0 !important;
  }
  /* 表格打印优化 */
  table {
    border-collapse: collapse;
    width: 100%;
  }
  th, td {
    border: 1px solid #ddd;
    padding: 8px;
    text-align: left;
  }
  th {
    background-color: #f2f2f2;
  }
}
  • 第三步:绑定打印点击事件,在你现有代码的<script>标签内插入以下代码
$('#printBtn').on('click', function() {
  window.print();
})

点击按钮即可直接调用浏览器的打印功能,选择打印机或者导出为本地PDF都可直接完成。

二、自定义导出PDF功能实现

推荐使用轻量的DomPDF类库实现,操作简单:

  • 第一步:安装DomPDF
    如果你会用composer,直接在项目根目录执行命令:composer require dompdf/dompdf
    如果不会用composer,直接下载DomPDF的源码压缩包,解压到你的项目目录即可。
  • 第二步:新建PDF导出接口文件export_inventory_pdf.php,代码如下(数据库字段和表名根据你自己的实际结构调整)
<?php
session_start();
if(!isset($_SESSION['login_id'])) {
  header('location:login.php');
  exit;
}
// 引入DomPDF,如果你是手动下载的源码,路径改成你自己的存放路径
require 'vendor/autoload.php'; 
use Dompdf\Dompdf;

// 连接数据库,替换成你自己的数据库配置
$conn = new mysqli('localhost', '数据库用户名', '数据库密码', '数据库名');
if ($conn->connect_error) {
  die("数据库连接失败: " . $conn->connect_error);
}

// 查询库存数据,表名和字段调整为你自己的
$sql = "SELECT * FROM inventory";
$result = $conn->query($sql);

// 拼接PDF的HTML内容
$html = '
<h1>库存报表</h1>
<table border="1" cellpadding="5" cellspacing="0" width="100%">
  <thead>
    <tr>
      <th>商品ID</th>
      <th>商品名称</th>
      <th>库存数量</th>
      <th>单价</th>
      <th>入库时间</th>
    </tr>
  </thead>
  <tbody>
';
if ($result->num_rows > 0) {
  while($row = $result->fetch_assoc()) {
    $html .= '<tr>';
    $html .= '<td>'.$row['id'].'</td>';
    $html .= '<td>'.$row['product_name'].'</td>';
    $html .= '<td>'.$row['quantity'].'</td>';
    $html .= '<td>'.$row['price'].'</td>';
    $html .= '<td>'.$row['create_time'].'</td>';
    $html .= '</tr>';
  }
}
$html .= '
  </tbody>
</table>
';

// 生成并下载PDF
$dompdf = new Dompdf();
$dompdf->loadHtml($html);
// 设置纸张大小,内容多可以把第二个参数改成landscape改为横向打印
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
// 导出文件名自动带日期
$dompdf->stream('库存报表_'.date('Y-m-d').'.pdf', array('Attachment' => 1));
?>
  • 第三步:添加导出按钮和绑定事件
    先在报表页面的按钮组里加导出按钮:
<button id="exportPdfBtn" class="btn btn-success">导出PDF</button>

再在现有<script>标签里加绑定代码:

$('#exportPdfBtn').on('click', function() {
  window.open('export_inventory_pdf.php', '_blank');
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 01:27:07