Angular学习笔记41:在Angular使用pdfmake,解决中文字体乱码和报错问题

在Angular6升级后,使用pdfmake遇到vfs_fonts.js不兼容的问题,通过创建自定义中文字体包并替换原文件,解决了乱码和报错。步骤包括:克隆官网脚本,下载字体包,修改生成的vfs_fonts.js文件,最后将其放入node_modules目录。
摘要由CSDN通过智能技术生成

前端学习笔记: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 下;
重新运行保存,发现顺利成功解决问题。

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值