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

Angular中基于json-server实现表格PDF导出方案咨询

Angular从json-server获取数据实现PDF导出方案

你已经通过getProducts()把json-server的数据拉取到本地products数组里了,所以导出PDF的逻辑和处理本地数组完全一致,不需要额外对接接口。下面是基于jspdf+jspdf-autotable的落地实现:

1. 安装依赖

在项目根目录执行命令:

npm install jspdf jspdf-autotable

2. 实现PDF导出逻辑

修改product.component.ts文件,添加必要导入并完善exportPdf方法:

首先在文件顶部新增导入:

import jsPDF from 'jspdf';
import 'jspdf-autotable';

然后替换空的exportPdf方法:

exportPdf(): void {
  // 创建PDF实例
  const doc = new jsPDF('p', 'mm', 'a4');
  
  // 设置文档标题
  doc.setFontSize(18);
  doc.text('Sector产品列表', 14, 20);
  
  // 定义表头和对应数据字段
  const tableHeaders = [['Code', 'Explanation']];
  const tableData = this.products.map(product => [
    product.code,
    product.explanation
  ]);
  
  // 生成带样式的表格
  (doc as any).autoTable({
    head: tableHeaders,
    body: tableData,
    startY: 30, // 表格起始垂直位置
    theme: 'striped',
    headStyles: {
      fillColor: '#2196F3',
      textColor: '#fff'
    }
  });
  
  // 触发文件下载
  doc.save(`products_export_${new Date().getTime()}.pdf`);
}

3. 优化按钮图标(可选)

把PDF按钮的图标换成对应样式:

<button pButton pRipple type="button" class="p-button-outlined " icon="pi pi-file-pdf" (click)="exportPdf()" pTooltip="PDF" tooltipPosition="bottom"></button>

补充:导出全量数据(跳过分页)

如果需要导出json-server中的所有数据(而非当前分页展示的内容),可以在导出时重新拉取完整数据集:

exportPdf(): void {
  this.productService.getProducts().subscribe(products => {
    const doc = new jsPDF('p', 'mm', 'a4');
    doc.setFontSize(18);
    doc.text('Sector全量产品列表', 14, 20);
    
    const tableHeaders = [['Code', 'Explanation']];
    const tableData = products.map(product => [product.code, product.explanation]);
    
    (doc as any).autoTable({
      head: tableHeaders,
      body: tableData,
      startY: 30,
      theme: 'striped'
    });
    
    doc.save(`products_full_export_${new Date().getTime()}.pdf`);
  });
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 05:04:58