VUE - pdfmake的中文字库支持

前端VUE导出pdf。

        jspdf这个插件对中文支持不够友好,用html的canvas转图片后还是很模糊。最终选用了pdfmake插件。

使用

1.引入pdf

npm install pdfmake  --save

2.页面import

import pdfMake from 'pdfmake/build/pdfmake';
import pdfFonts from 'pdfmake/build/vfs_fonts';
pdfMake.vfs = pdfFonts.pdfMake.vfs;

3.简单functionDemo

      exportPdf(){
        var fileName = 'test.pdf'

        const docDefinition = {
          content: [
            '测试测试',
            '工单号:12345',

          ],
        };
        pdfMake.createPdf(docDefinition).download(fileName)

      },

4.中文字库支持

官方文档icon-default.png?t=N7T8https://pdfmake.github.io/docs/0.1/fonts/custom-fonts-client-side/vfs/

1. create a new vfs_fonts.js containing your font files 
Install pdfmake npm install pdfmake
Go to package directory ./node_modules/pdfmake/
Create the examples/fonts subdirectory in your pdfmake code directory, if it doesn’t already exist.
Copy your fonts (and other files you wish to embed) into the examples/fonts subdirectory.
Run command node build-vfs.js "./examples/fonts". Or run node build-vfs.js to show help.
Include your new build/vfs_fonts.js file in your code (in the same way you include pdfmake.js or pdfmake.min.js).
The above steps embeds all files from examples/fonts (into a local key/value variable pdfMake.vfs) - not only fonts. Which means you could put images in there, run node build-vfs.js "./examples/fonts, and reference them by filename in your doc-definition object.

You don’t need to reference the files in examples/fonts anymore because all files have been copied to the vfs_fonts.js.

4.1 下载字库,我使用的是微软雅黑

4.2 打开项目的node_modules->pdfmake

      创建/examples/fonts 文件夹,插入字库文件

      cmd执行 node build-vfs.js "./examples/fonts"

4.3页面引入字体

import pdfMake from 'pdfmake/build/pdfmake';
import pdfFonts from 'pdfmake/build/vfs_fonts';
pdfMake.fonts = {
  msyh: {
    normal: 'msyh.ttf',
    bold: 'msyh.ttf',
    italics: 'msyh.ttf',
    bolditalics: 'msyh.ttf'
  }
};
pdfMake.vfs = pdfFonts.pdfMake.vfs;

4.4使用字体

      exportPdf(){
        var fileName = 'test.pdf'

        const docDefinition = {
          content: [
            '测试测试',
            '工单号:12345',

          ],
          defaultStyle: {
            font: 'msyh'
          },
        };
        pdfMake.createPdf(docDefinition).download(fileName)

      },

如果报错 roboto字体找不不到:

 1.打开pdfmake github 项目

GitHub - bpampuch/pdfmake: Client/server side PDF printing in pure JavaScript

    pdfmake/examples/fonts/ 下的roboto字体 跟你的字体都放在 4.2 中执行

  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值