Angular 4/5中如何从JSON接口响应生成PDF文件
在Angular 4/5中从JSON接口响应生成PDF文件
嘿,我来帮你搞定在Angular 4/5里把接口返回的JSON数据转成PDF这件事!结合你给出的代码片段,我整理了完整的实现方案,一步步来:
1. 先安装必要的依赖
我们会用到jsPDF来生成PDF核心文件,还有jsPDF-autotable来快速创建表格(比手动计算坐标画表格省心太多),执行下面的命令安装:
npm install jspdf jspdf-autotable --save
2. 在组件中引入依赖
在你要实现PDF生成的组件文件顶部,引入这两个库:
import * as jsPDF from 'jspdf'; import 'jspdf-autotable';
3. 完善PDF生成方法
你给出的代码片段已经有了雏形,我把它补全并优化,确保能正确处理接口返回的JSON数据:
import { Component, OnInit } from '@angular/core'; import * as jsPDF from 'jspdf'; import 'jspdf-autotable'; @Component({ selector: 'app-pdf-generator', templateUrl: './pdf-generator.component.html', styleUrls: ['./pdf-generator.component.css'] }) export class PdfGeneratorComponent implements OnInit { // 存储接口返回的JSON数据数组 finalArList: any[] = []; ngOnInit() { // 这里替换成你的实际HTTP请求,获取接口数据 this.fetchDataFromApi(); } // 模拟接口请求(实际项目中用HttpClient.get()请求接口,在subscribe里赋值) fetchDataFromApi() { this.finalArList = [ { dischargeDate: '2024-05-01', caseNo: 'CASE-001', patientName: 'John Doe', hospitalName: 'City General Hospital', payor: 'ABC Insurance', totalDoctorFee: '¥500', toBeCollected: '¥300' }, { dischargeDate: '2024-05-02', caseNo: 'CASE-002', patientName: 'Jane Smith', hospitalName: 'Downtown Medical Center', payor: 'XYZ Health', totalDoctorFee: '¥700', toBeCollected: '¥450' } ]; } convert() { // 初始化PDF实例,默认是纵向A4纸 const doc = new jsPDF(); // 定义表格的列标题 const col = ['DischargeDate', 'Case Number', 'Patient Name', 'Hospital Name', 'Payor', 'Total Doctor Fee', 'To be Collected']; const rows: any[] = []; // 遍历接口返回的数据,把每个对象的字段提取成表格行 this.finalArList.forEach(element => { const tempRow = [ element.dischargeDate, element.caseNo, element.patientName, element.hospitalName, element.payor, element.totalDoctorFee, element.toBeCollected ]; rows.push(tempRow); }); // 添加PDF标题 doc.text('Patient Billing Summary', 14, 15); // 使用autotable生成表格,自动处理列宽、分页 (doc as any).autoTable({ head: [col], // 表头 body: rows, // 表格内容 startY: 20, // 表格从Y轴20的位置开始,避免和标题重叠 headStyles: { fillColor: '#4CAF50' } // 自定义表头背景色 }); // 保存PDF文件,或者用doc.output('dataurlnewwindow')在新窗口打开 doc.save('patient-billing-summary.pdf'); } }
关键要点说明
- 数据对应:确保接口返回的
finalArList数组里的每个对象,字段和你定义的列标题一一对应,不然表格内容会错位 - 样式自定义:
autotable支持很多配置,比如修改表头样式、单元格字体、列宽等,你可以根据需求调整 - 自动分页:如果接口返回的数据量很大,
autotable会自动帮你分页,不需要额外写逻辑 - PDF参数调整:初始化
jsPDF时可以修改参数,比如new jsPDF('landscape', 'mm', 'a4')设置横向A4纸
模板端调用方法
在组件的HTML模板里,加一个按钮触发convert方法就行:
<button (click)="convert()">生成PDF</button>
内容的提问来源于stack exchange,提问作者Nancy
相关产品推荐
相关产品推荐

