前端导出PDF之pdfmake

pdfmake通过编辑特定格式的 pdf描述对象,传给pafmake ,来生成pdf

默认pdfmake不支持中文

如何支持中文

要支持中文,就需要配置中文字体。根据文档介绍有两种方式:1.使用在线字体配置。2.使用本地 vfs(virtual file system)配置字体。本文介绍第二种。

文档描述的步骤:

  • Install pdfmake npm install pdfmake

    安装 pdfmake

  • Go to package directory ./node_modules/pdfmake/

    进入 ./node_modules/pdfmake/目录

  • Create the examples/fonts subdirectory in your pdfmake code directory, if it doesn’t already exist.

    在pdfmake目录下创建 examples/fonts 子目录

  • Copy your fonts (and other files you wish to embed) into the examples/fonts subdirectory.

    把你要使用的字符 .ttf 文件放入 examples/fonts 目录下,中文字体文件都比较大,可以进入电脑的字体文件夹,找一个小点的放进去或者下载自己想要的字体

  • Run command node build-vfs.js "./examples/fonts". Or run node build-vfs.js to show help.

    在pdfmake目录执行 node build-vfs.js "./examples/fonts"

  • Include your new build/vfs_fonts.js file in your code (in the same way you include pdfmake.js or pdfmake.min.js).

    然后在build文件夹下会生成 vfs_fonts.js文件,这个文件就是我们要使用的字体文件,可以打开这个文件,能看到字体名称等信息

以上我们就生成了中文字体

如何使用
// 在项目里引入pdfmake
import pdfMake from "pdfmake/build/pdfmake";

// 我把上面生成的字体放入了 vue 中的static文件夹,我使用的是FZYTK.TTF
// 这样直接引入就可以,不需要额外引入原字体文件(FZYTK.TTF)
const vfs_fonts = require('../xxx/static/vfs_fonts');
pdfMake.vfs = vfs_fonts;

// 定义字体 
pdfMake.fonts = {
    // webfont是字体名,可以自定义,下面需要用这个名字配置字体
    webfont: {
        // FZYTK.TTF 这个文件已经在 我们生成的 vfs_font.js 文件中,且已经引入,所以可以直接使用
        normal: "FZYTK.TTF",
        bold: "FZYTK.TTF",
        italics: "FZYTK.TTF",
        bolditalics: "FZYTK.TTF",
    },
    // 可以定义多个字体
    anotherFontName: {
     (...)
    },
};

// 下面我们来定义 pdfmake需要用的 pdf文件描述对象
// 这个描述对象 具体的字段可以参考官方文档
var docDefinition = {
    content: "这是一段中文。welcome to China",
    defaultStyle: {
        // 设置我们定义的字体为默认字体
        font: "webfont",
    },
};

pdfMake.createPdf(docDefinition).download("文件名", () => {
    console.log("complete");
});
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值