- 首先,您需要获取 ttf 字体,并将其转换为
有用的东西。使用类似工具对其进行 Base64 编码https://www.base64decode.org/(请务必切换到encode和
向下滚动一点以将文件拖放到那里)
- 现在您有一个如下文件:“encoded-20200619201035.txt”
- 创建一个新文件,我称之为 GnuMICR.ttf.Base64.encoded.ts
- 将编码文件的全部内容复制/粘贴到您导出的变量中。 MICR 是一种很小的字体,它有超过 6,000 个字符长,所以你看到的“.....”是 6,000 个章程,我不会用它来炸毁 stackoverflow,这会让它变得不可读
GnuMICR.ttf.Base64.encoded.ts 文件仅包含这一行:
export const strGnuMICR:string = "AAEAAAALAIAAA.....FDAUQCQ1IAAAA=";
现在,在您正在使用的主代码中,您需要在顶部包含常规 pdfmake:
import pdfMake from 'pdfmake/build/pdfmake'
import pdfFonts from 'pdfmake/build/vfs_fonts'
以及导入你的字体(我的字体位于我创建的一个名为 fonts 的子目录中。不要使用 asset 子目录,它将在 dev 中工作,但不会被拉入以进行正确的构建):
import { strGnuMICR } from './../../fonts/GnuMICR.ttf.Base64.encoded'
pdfmake 谈论“虚拟文件系统”,当您看到变量“时就暗示了这一点”vfs_fonts”,但实际上,它只是一个数组。您还会看到默认值是像“Roboto-Regular.ttf”这样的文件名,但这又不是虚拟文件系统上的文件:“Roboto-Regular.ttf”只是vfs_fonts.js 数组中数据的名称。为了清楚起见,您没有对实际文件执行任何操作,它全部使用您已经构建的 Base64 编码变量。
深入到您在主代码中进行工作的位置:
generatePDF(){
// this adds our base64 encoded data to the existing 'virtual file system'
pdfFonts.pdfMake.vfs['GnuMICR_b64']=strGnuMICR
// you're going to wipe out the standard stuff when you create this
// variable, so we need to add the stock Roboto fonts back in. I
// set all fonts to the same thing, as "italic MICR" would be silly.
pdfMake.fonts = {
Roboto: {
normal: 'Roboto-Regular.ttf',
bold: 'Roboto-Medium.ttf',
italics: 'Roboto-Italic.ttf',
bolditalics: 'Roboto-MediumItalic.ttf'
},
GnuMICR:{
normal: 'GnuMICR_b64',
bold: 'GnuMICR_b64',
italics: 'GnuMICR_b64',
bolditalics: 'GnuMICR_b64'
},
}
// that's it, all the install work is done
// build the pdf, using our new font via a style we define
let docDefinition =
{
content: [
{text:'regular Roboto text'},
{text:'and a line of MICR text follows:'},
{text:'C11111111C A222222222A 333333333C 0123456789',style:'micr'},
],
styles:{
micr:{
font: 'GnuMICR',
fontSize: 12,
}
},
defaultStyle:{
font: 'Roboto',
fontSize: 15,
}
};
// annnnnnd generate that PDF!!
pdfMake.createPdf(docDefinition).open();
}
好处:
- 不必安装/对抗 gulp 工具
- 您的字体存在于您的代码库中,因此可以进行版本控制
- 挺容易
缺点:
- 您不会将此字体添加到系统范围内可用的 pdfmake“库”中,因此每次编写一些代码来制作 PDF 时都会执行此操作。如果您正在编写数十种不同的 PDF 制作实用程序,那么其他方法可能更适合您。如果您只需要制作一个或几个,没什么大不了的。