//引入插件
import jsPDF from "jspdf";
import autoTable from "jspdf-autotable";
//通过canvas将图片转码base64URL
getBase64(img,cb){
const canvas=document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
const context = canvas.getContext("2d");
context.drawImage(img,0,0,img.width,img.height);
const base64URL= canvas.toDataURL("image/png",1);
cb(base64URL)
},
//打印方法
async exportpdf(){
const doc = new jsPDF() var img_obj=""
const img = document.getElementByid("img"); //获取png格式图片
this.getBase64(img,(base64Data)=>{ img_obj = base64Data })//通过回调拿到base64URL
doc.addFont("static/fonts/FZHTJW.TTF",'demo','normal') //引用字体模板
doc.setFont("demo",'normal')//字体设置
doc.text("打印结果",84,10)
doc.autoTable({
html:'#tb1',
styles:{
font:'demo'
},
theme:'grid'
})
doc.text("详细信息”,94,doc.autoTable.previous .finalY +10)
doc.autoTable({
html:'#tb2',//获取html标签元素,一个完整的table
startY: doc.autoTable.previous.finalY +20,
styles:{
font: 'demo',
maxCellWidth:20
}
theme:'grid',//表格带边框
columnStyles:{//表头列宽度
0:{cellwidth:30}, 1:{cellwidth:30}, 2:{cellwidth:30}, 3:{cellwidth:30}, 4:{cellwidth:30},
5:{cellwidth:30}, 6:{cellwidth:30}
},
didDrawCell:(data)=>{//绘图钩子函数
const row=data.table.body.length-2
if(data.row.index==row && data.column.index==3){
doc.addImage(img_obj,'png' ,data.cell.x+2,data.cell.y+1,30,14)
}
}
})
doc.save('export_document.pdf')
},
Vue2使用 jsPDF 及autoTable 插件 打印表格及图片
最新推荐文章于 2024-08-12 11:14:36 发布