使用pdfmake库通过NestJS typescript生成PDF

问题描述 投票:0回答:1

我无法找到有关如何在 Nest js 中实现此库的信息,因为文档不完整,因此我将其放在这里,您需要首先 npm install pdfmake --save 和 npm install @types/pdfmake --save-dev 然后是这个使用节点 20 的代码对我有用

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 as any).vfs = pdfFonts.pdfMake.vfs;
  }
  getHello() {
    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?'],
            ],
          },
        },
      ],
    };

    const pdfDoc = pdfMake.createPdf(dd);

    pdfDoc.getBuffer((buffer) => {
      fs.writeFileSync('pdf/output.pdf', buffer);
      console.log('PDF saved successfully');
    });

    return 'Hello World!';
  }
}

只是为了让其他人实现的方式是一个从后端生成pdf的非常好的库

pdf nestjs pdfmake
1个回答
0
投票

在另一个安装中,这对我来说适用于nodejs20和nest版本10.4.5

import { Injectable } from '@nestjs/common';
import * as pdfFonts from 'pdfmake/build/vfs_fonts';
import * as fs from 'fs';
import * as pdfMake from 'pdfmake/build/pdfmake';
import { TDocumentDefinitions } from 'pdfmake/interfaces';

© www.soinside.com 2019 - 2024. All rights reserved.