前端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.中文字库支持
官方文档https://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 中执行