pdfmake 生成pdf 下载 引入中文字体

 

第一步:

网上下载字体文件  我用的微软雅黑如:msyh.ttf  注意必须是 *.ttf后缀的

第二步:

打开项目的node_modules->pdfmake

创建/examples/fonts 文件夹,

把字体库拷贝到examples/fonts

然后在目录node_modules->pdfmake里

cmd执行 node build-vfs.js "./examples/fonts"

 结束后,会发现 pdfmake/build/vfs_fonts.js 文件变的很大,打开里面多了一行

 说明安装成功,开始使用

第三步:

import * as pdfMake from 'pdfmake/build/pdfmake';
import * as pdfFonts from 'pdfmake/build/vfs_fonts';

pdfMake.vfs = pdfFonts.pdfMake.vfs;
pdfMake.fonts = {
  msyh: {
    normal: 'msyh2.ttf',
    bold: 'msyh2.ttf',
    italics: 'msyh2.ttf',
    bolditalics: 'msyh2.ttf',
  },
};

  

export const exportPdf = async (res: any, filename: string, cont: any) => {
  const documentDefinition = {
    pageSize: 'A4',
    content: [cont, 'FDS'],
    defaultStyle: {
      font: 'msyh',
    },
    styles: {
      cover: {
        fontSize: 32,
        alignment: 'center',
        color: '#4472C4',
        margin: [0, 180, 0, 0],
      },
      tableExample: {
        fontSize: 12,
        alignment: 'center',
      },
      header: {
        bold: true,
        margin: [0, 4, 0, 0],
      },
    },
  };

  const pdf = pdfMake.createPdf(documentDefinition);
  pdf.getBase64((data) => {
    res.writeHead(200, {
      'Content-Type': 'application/pdf',
      'Content-Disposition': `attachment;filename=${filename}.pdf`,
    });
    const buffer = Buffer.from(data.toString('utf-8'), 'base64');
    res.end(buffer);
  });
};

  

posted @ 2024-04-25 18:08  James2019  阅读(206)  评论(0编辑  收藏  举报