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);
  });
};

  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章