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

Angular Ignite UI的Igx-Grid组件如何实现PDF导出功能

Igx-Grid PDF导出解决方案

原生导出能力实现

你使用的Angular 12对应的Ignite UI for Angular版本已经内置PDF导出服务,无需额外接入第三方工具即可完成导出,实现步骤如下:

  • 在对应模块中导入导出依赖并注册服务
// 业务模块的module.ts文件
import { NgModule } from '@angular/core';
import { IgxGridPdfExportModule } from 'igniteui-angular';
import { IgxPdfExportService } from 'igniteui-angular/services';

@NgModule({
  imports: [
    // 原有其他导入项
    IgxGridPdfExportModule
  ],
  providers: [IgxPdfExportService]
})
export class YourBusinessModule { }
  • 在组件中调用导出服务
    你现有模板代码已经给表格声明了#grid模板引用,直接在组件逻辑中获取实例调用导出即可:
<!-- 组件模板,在原有表格基础上新增导出按钮即可 -->
<igx-grid #grid id="grid" [data]="liste" [allowFiltering]="true"  [autoGenerate]="true"></igx-grid>
<button (click)="exportGridToPdf()">导出PDF</button>
// 组件ts文件
import { Component, ViewChild } from '@angular/core';
import { IgxGridComponent, IgxPdfExportService, IPdfExportOptions } from 'igniteui-angular';

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html'
})
export class YourComponent {
  @ViewChild('grid', { static: true }) grid: IgxGridComponent;
  public liste: any[] = []; // 你的表格数据源

  constructor(private pdfExportService: IgxPdfExportService) {}

  exportGridToPdf() {
    const exportConfig: IPdfExportOptions = {
      fileName: '表格导出结果.pdf',
      exportAllPages: true, // 开启分页时设置为true可导出全部页数据
      paperSize: 'A4'
    };
    this.pdfExportService.export(this.grid, exportConfig);
  }
}

原生导出服务支持自定义列过滤、样式配置、页眉页脚添加等能力,可根据业务需求调整IPdfExportOptions的参数即可。


备选实现方案

如果存在版本适配问题无法使用官方导出服务,可以用jsPDF + html2canvas组合实现自定义导出:

  • 先安装依赖包
npm install jspdf html2canvas --save
  • 在组件中实现导出逻辑
import jsPDF from 'jspdf';
import html2canvas from 'html2canvas';

// 组件类中新增导出方法
public async exportGridToPdf() {
  const gridDom = document.getElementById('grid');
  // 生成高清canvas
  const canvas = await html2canvas(gridDom, { scale: 2, useCORS: true });
  const imgData = canvas.toDataURL('image/png');
  const pdf = new jsPDF('p', 'mm', 'a4');

  const pdfWidth = 210; // A4纸宽度(单位mm)
  const pdfHeight = 297; // A4纸高度(单位mm)
  const imgHeight = (canvas.height * pdfWidth) / canvas.width;
  let remainingHeight = imgHeight;
  let position = 0;

  pdf.addImage(imgData, 'PNG', 0, position, pdfWidth, imgHeight);
  remainingHeight -= pdfHeight;

  // 数据超过一页时自动分页
  while (remainingHeight > 0) {
    position = remainingHeight - imgHeight;
    pdf.addPage();
    pdf.addImage(imgData, 'PNG', 0, position, pdfWidth, imgHeight);
    remainingHeight -= pdfHeight;
  }

  pdf.save('表格导出结果.pdf');
}

该方案导出的PDF内容为图片格式,不支持文本选中复制,仅作为降级方案使用。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 17:36:03