如何在NestJS(TypeScript)中使用pdfmake库生成PDF?
在NestJS中使用pdfmake生成PDF的实现方案
由于pdfmake官方文档对NestJS环境下的实现说明不完善,这里分享一套在Node 20环境下验证有效的实现方法:
安装依赖
首先执行以下命令安装所需包:
npm install pdfmake --save npm install @types/pdfmake --save-dev
实现代码
在NestJS的Service中编写如下代码:
import { Injectable } from '@nestjs/common'; import pdfFonts from 'pdfmake/build/vfs_fonts'; import * as fs from 'fs'; import pdfMake from 'pdfmake/build/pdfmake'; import { TDocumentDefinitions } from 'pdfmake/interfaces'; @Injectable() export class AppService { constructor() { // 注册pdfmake所需的字体文件 (pdfMake as any).vfs = pdfFonts.pdfMake.vfs; } generatePdf() { // 定义PDF文档内容结构 const dd: TDocumentDefinitions = { content: [ 'First paragraph', 'Another paragraph, this time a little bit longer to make sure, this line will be divided into at least two lines', { text: 'This paragraph will have a bigger font', fontSize: 15, color: 'blue', }, { columns: [ { text: 'This is a column', }, { text: 'Another column', }, ], }, { text: 'Tables', style: 'header' }, 'Official documentation is in progress, this document is just a glimpse of what is possible with pdfmake and its layout engine.', { text: 'A simple table (no headers, no width specified, no spans, no styling)', style: 'subheader', }, 'The following table has nothing more than a body array', { style: 'tableExample', table: { body: [ ['Column 1', 'Column 2', 'Column 3'], ['One value goes here', 'Another one here', 'OK?'], ], }, }, ], }; // 创建PDF实例并生成文件 const pdfDoc = pdfMake.createPdf(dd); pdfDoc.getBuffer((buffer) => { // 确保pdf目录存在,避免写入失败 if (!fs.existsSync('pdf')) { fs.mkdirSync('pdf'); } fs.writeFileSync('pdf/output.pdf', buffer); console.log('PDF saved successfully'); }); return 'PDF generated successfully!'; } }
关键说明
- 构造函数中注册字体文件是必要操作,否则会出现字体加载失败的问题
- 示例中通过
getBuffer获取PDF的Buffer数据并写入本地文件,你也可以直接将Buffer返回给前端作为下载响应 - pdfmake支持文本、表格、多列布局等多种自定义配置,是一款功能强大的后端PDF生成工具
内容的提问来源于stack exchange,提问作者Jeferson Narvaez
相关产品推荐
相关产品推荐

