pdfmake通過編輯特定格式的 pdf描述對(duì)象趾盐,傳給pafmake ,來生成pdf
默認(rèn)pdfmake不支持中文
如何支持中文
要支持中文,就需要配置中文字體斩狱。根據(jù)文檔介紹有兩種方式:1.使用在線字體配置掖疮。2.使用本地 vfs(virtual file system)配置字體初茶。本文介紹第二種。
文檔描述的步驟:
-
Install pdfmake
npm install pdfmake
安裝 pdfmake
-
Go to package directory
./node_modules/pdfmake/
進(jìn)入
./node_modules/pdfmake/
目錄 -
Create the
examples/fonts
subdirectory in your pdfmake code directory, if it doesn’t already exist.在pdfmake目錄下創(chuàng)建
examples/fonts
子目錄 -
Copy your fonts (and other files you wish to embed) into the
examples/fonts
subdirectory.把你要使用的字符 .ttf 文件放入
examples/fonts
目錄下浊闪,中文字體文件都比較大恼布,可以進(jìn)入電腦的字體文件夾螺戳,找一個(gè)小點(diǎn)的放進(jìn)去或者下載自己想要的字體 -
Run command
node build-vfs.js "./examples/fonts"
. Or runnode build-vfs.js
to show help.**在pdfmake目錄執(zhí)行
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
orpdfmake.min.js
).然后在
build
文件夾下會(huì)生成vfs_fonts.js
文件,這個(gè)文件就是我們要使用的字體文件折汞,可以打開這個(gè)文件倔幼,能看到字體名稱等信息
以上我們就生成了中文字體
如何使用
// 在項(xiàng)目里引入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是字體名凤藏,可以自定義,下面需要用這個(gè)名字配置字體
webfont: {
// FZYTK.TTF 這個(gè)文件已經(jīng)在 我們生成的 vfs_font.js 文件中堕伪,且已經(jīng)引入揖庄,所以可以直接使用
normal: "FZYTK.TTF",
bold: "FZYTK.TTF",
italics: "FZYTK.TTF",
bolditalics: "FZYTK.TTF",
},
// 可以定義多個(gè)字體
anotherFontName: {
(...)
},
};
// 下面我們來定義 pdfmake需要用的 pdf文件描述對(duì)象
// 這個(gè)描述對(duì)象 具體的字段可以參考官方文檔
var docDefinition = {
content: "這是一段中文。welcome to China",
defaultStyle: {
// 設(shè)置我們定義的字體為默認(rèn)字體
font: "webfont",
},
};
pdfMake.createPdf(docDefinition).download("文件名", () => {
console.log("complete");
});