pdfmake 打包导入使用中文字体,解决中文乱码问题

发布时间 2023-08-08 16:46:24作者: wuzx-blog

本示例以宋体为例:

1、首先去windows里拷贝出字体库,文件夹:C:\Windows\Fonts,例如使用宋体:Simsun.ttf,

2、下载 pdfmake-master 源码

地址:https://codeload.github.com/bpampuch/pdfmake/zip/refs/heads/master

3、使用Visual Studio Code,打开源码

4、环境需要安装node.js

5、执行npm install安装必要的包

 6、将字体库拷贝到源码的examples/fonts,fonts文件夹内容先清空在拷贝

7、运行命令node build-vfs.js "./examples/fonts"  ,实现将字体导入到vfs_fonts.js文件中,生成个新文件

8、将build文件夹拷贝到test处使用

test.html源码

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 
 4 <head>
 5   <meta charset="UTF-8">
 6   <meta http-equiv="X-UA-Compatible" content="IE=edge">
 7   <meta name="viewport" content="width=device-width, initial-scale=1.0">
 8   <title>Document</title>
 9   <script src="build/pdfmake.min.js"></script>
10   <script src="build/vfs_fonts.js"></script>
11   <!--自己下载一个-->
12   <script src="build/jquery.min.js"></script>
13 </head>
14 
15 <body>
16   <button class="btn">下载</button>
17 </body>
18 
19 <script>
20  
21   pdfMake.fonts = {
22     Roboto: {
23          normal: 'Roboto-Regular.ttf',
24          bold: 'Roboto-Medium.ttf',
25          italics: 'Roboto-Italic.ttf',
26          bolditalics: 'Roboto-Italic.ttf'
27      },
28     Simsun: {
29         normal: 'Simsun.ttf',
30         bold: 'Simsun.ttf',
31         italics: 'Simsun.ttf',
32         bolditalics: 'Simsun.ttf',
33     }
34   };
35   $('.btn').on('click', function () {
36     let dd = {
37       content: [
38         '中英文测试',
39         'Another paragraph, this time a little bit longer to make sure, this line will be divided into at least two lines'
40       ],
41       defaultStyle: {
42         font: 'Simsun'
43       }
44     };
45     pdfMake.createPdf(dd).download();
46   })
47 </script>
48 
49 </html>

目录结构

build文件夹

Demo示例源码分享如下,直接下载使用。

https://files.cnblogs.com/files/wuzexin/pdfmake-%E5%AE%8B%E4%BD%93demo.zip?t=1691484187&download=true 

摸索了半天的成果,对你有帮助的话就给点个赞,评论一下呗!