1.下载插件
npm install html2canvas jspdf --save
2.插入插件
import html2canvas from 'html2canvas';
import jspdf from 'jspdf';
3.方法
downPdf() {
var ab = document.getElementById('main')
// 定义dom 宽度,高度
var width = ab.offsetWidth /4;
var height = ab.offsetHeight / 4 ;
// 定一个大盒子
html2canvas(ab, {
dpi: 900,
scrollY: 0,
scrollX: -10,
useCORS: true,
}).then((canvas) => {
console.log("canvas", canvas)
var context = canvas.getContext('2d')
console.log("context", context)
// 这段代码去除锯齿,会使图片变得清晰,结合scale放大处理
context.mozImageSmoothingEnabled = false;
context.webkitImageSmoothingEnabled = false;
context.msImageSmoothingEnabled = false;
context.imageSmoothingEnabled = false;
// 返回一个包含图片展示的 数据URL 1.照片格式 2.清晰度
var pageData = canvas.toDataURL('image/jpeg', 1.0);
var img = new Image()
img.src = pageData;
img.onload = () => {
img.width = img.width / 2
img.height = img.height / 2
console.log(img.width, '------ img.width');
console.log(img.height, '------img.height');
img.style.transform = 'scale(0.5)'
if (width > height) {
// 此可以根据打印的大小进行自动调节
// eslint-disable-next-line
var pdf = new jspdf('l', 'mm', [width * 0.85, height * 0.85]);
} else {
// eslint-disable-next-line
var pdf = new jspdf('p', 'mm', [width * 0.85, height * 0.85]);
}
//在PDF文件上插入图片的函数,它提供了控制图片大小、压缩质量、图片旋转度数等属性
pdf.addImage(pageData, 'jpeg', 0, 0, width * 0.85, height * 0.85);
//h5在这就可以保存pdf
pdf.save('安全服务协议' + '.pdf');
//内嵌到微信小程序
var blob = pdf.output("datauristring");
console.log(wx, 'wx')
}
}).catch((r) => {
console.log(r);
})
},