在前端学习笔记:angular4中将html导出为pdf中,使用了pdfmake的源代码克隆或下载到本地之后,使用gulp解决乱码问题,但是在升级Angular6之后,发现生成的vfs_fonts.js却不能用了。
经pdfmake官网,决定使用shell 脚本来创建自定义的中文字体包。
将官网的脚本拷贝到本地,保存文件
- 非mac的版本
#!/bin/sh
if [ -t 1 ]; then
target="vfs_fonts.js"
else
target="/dev/stdout"
fi
(
echo -n "this.pdfMake = this.pdfMake || {}; this.pdfMake.vfs = {"
for file in "$@"; do
file=$1
shift
echo -n '"'
echo -n "$(basename $file)"
echo -n '":"'
echo -n "$(base64 -w 0 $file)"
echo -n '"'
if [ "$#" -gt 0 ]; then
echo -n ","
fi
done
echo -n "};"
) > "$target"
- mac版本
#!/bin/sh
if [ -t 1 ]; then
target="vfs_fonts.js"
else
target="/dev/stdout"
fi
(
echo -n "this.pdfMake = this.pdfMake || {}; this.pdfMake.vfs = {"
for file in "$@"; do
file=$1
shift
echo -n '"'
echo -n "$(basename $file)"
echo -n '":"'
echo -n "$(base64 -b 0 $file)"
echo -n '"'
if [ "$#" -gt 0 ]; then
echo -n ","
fi
done
echo -n "};"
) > "$target"
保存为:script.sh
下载字体包
将字体包下载到本地,方便之余,最好将字体文件,扩展名为:ttf的文件和script.sh放在同一个目录中。
然后执行:
sh script.sh ubuntu.ttf
有多个字体包,用空格隔开依次键入。然后当前目录下会生成一个vfs_fonts.js文件。
将vfs_fonts.js拷贝到node_modules目录中;
为了整个项目的构建和部署,最好将这个vfs_fonts.js文件放在assets目录中管理起来,
然后执行:
cp src/assets/pdfFonts/vfs_fonts.js node_modules/pdfmake/build/
这样就把原来的pdfmake中的vfs_fonts.js替换了。然后在项目中使用:
- 引入
import * as pdfMake from 'pdfmake/build/pdfmake.js';
import * as pdfFonts from 'pdfmake/build/vfs_fonts.js';
- 在某个方法中是使用
public testPdf() {
pdfMake.vfs = pdfFonts.pdfMake.vfs;
pdfMake.fonts = {
ubuntu: {
normal: 'ubuntu.ttf',
bold: 'ubuntu.ttf',
italics: 'ubuntu.ttf',
bolditalics: 'ubuntu.ttf'
}
};
const docDefinition = {
content: [
{text: '中文的Demo', fontSize: 15, font: 'ubuntu'},
]
};
pdfMake.createPdf(docDefinition).download('demo.pdf');
}
保存运行,会发现报错:
ERROR in ./node_modules/pdfmake/build/vfs_fonts.js 1:3
Module parse failed: Unexpected token (1:3)
You may need an appropriate loader to handle this file type.
> -n this.pdfMake = this.pdfMake || {}; this.pdfMake.vfs = {
| -n "
| -n ubuntu.ttf
遂打开vfs_fonts.js 发现是由于"-n" 影响导致的:
然后手动将这些删除整理。
然后在将这个文件复制到 node_modules 下;
重新运行保存,发现顺利成功解决问题。