不使用html2canvas的原因是因为在开发过程中,因为页面dom较多,html2canvas出现卡顿响应很慢,通过dom-to-image可以很好的解决该问题
在第一步将dom转换为图片后,需要通过jspdf将图片生成pdf
npm install dom-to-image
npm install jspdf --save
import domtoimage from 'dom-to-image';
import JsPDF from 'jspdf'
<canvas :width="canvasWidth" :height="canvasHeight" id="canvasDom" style="display:none;"></canvas>
onPrint() {
let that = this;
let node = document.getElementById('pdfDom');
console.log(node)
domtoimage.toJpeg(node, {
width: node.clientWidth,
height: node.clientHeight,
cacheBust: true,
style: {
margin: 0,
background: '#fff',
}
})
.then(function(dataUrl) {
that.canvasWidth = node.clientWidth;
that.canvasHeight = node.clientHeight;
let imgObj = new Image()
imgObj.src = dataUrl;
console.log(imgObj)
//待图片加载完后,将其显示在canvas上
imgObj.onload = function (img) {
console.log(img,'img')
let canvas = document.getElementById("canvasDom");
// canvas.width = node.clientWidth;
// canvas.height = node.clientHeight;
console.log(canvas.width,canvas.height,'canvas.width')
canvas.getContext("2d").drawImage(imgObj,0,0,that.canvasWidth,that.canvasHeight); //将图片绘制到canvas中
let contentWidth = canvas.width
let contentHeight = canvas.height
let pageHeight = contentWidth / 592.28 * 841.89 // a4纸的尺寸[592.28,841.89]
let leftHeight = contentHeight
let position = 0
let imgWidth = 595.28
let imgHeight = 592.28 / contentWidth * contentHeight
let pageData = canvas.toDataURL('image/jpeg', 1.0)
let PDF = new JsPDF('', 'pt', 'a4')
if (leftHeight < pageHeight) {
PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight) // 大于1页高度时分页
} else {
while (leftHeight > 0) {
PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
leftHeight -= pageHeight
position -= 841.89
if (leftHeight > 0) {
PDF.addPage()
}
}
}
PDF.save(that.htmlTitle + '.pdf')
}
return dataUrl
})
.catch(function(error) {
console.error('oops, dom2img went wrong!', error);
});
},