安装插件
npm install html2canvas --save
npm install jspdf --save
页面写好,最外层div设置高度为100vh,当下载时高度设置为auto,下载完成高度设置为100vh,zhuan
<div class="pdfBox" id="pdfBox">
<button @click="getPdf">下载pdf</button>
</div>
getPdf(reportName = 'exPdf', isDownload = true) {
let shareContent = document.querySelector('#printer');
shareContent.style.height = 'auto';
let pdfBox = document.querySelector('#pdfBox');
pdfBox.style.display = 'none';
let width = shareContent.clientWidth;
let height = shareContent.clientHeight;
let canvas = document.createElement('canvas');
let scale = 2;
canvas.width = width * scale;
canvas.height = height * scale;
canvas.style.width = shareContent.clientWidth * scale + 'px';
canvas.style.height = shareContent.clientHeight * scale + 'px';
window.pageYOffset = 0;
document.documentElement.scrollTop = 0
document.body.scrollTop = 0;
return new Promise((resolve, reject) => {
html2Canvas(document.querySelector('#printer'), {
allowTaint: true,
}).then((canvas) => {
var title = reportName;
let contentWidth = canvas.width*2;
let contentHeight = canvas.height*2;
//一页pdf显示html页面生成的canvas高度;
let pageHeight = (contentWidth / 592.28) * 841.89;
//未生成pdf的html页面高度
let leftHeight = contentHeight;
//页面偏移
let position = 0;
//a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
let imgWidth = 595.28;
let imgHeight = (592.28 / contentWidth) * contentHeight;
let pageData = canvas.toDataURL('image/jpeg', 1.0);
let PDF = new JsPDF('', 'pt', 'a4');
//有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89)
//当内容未超过pdf一页显示的范围,无需分页
if (leftHeight < pageHeight) {
PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight);
} else {
while (leftHeight > 0) {
PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight);
leftHeight -= pageHeight;
position -= 841.89;
//避免添加空白页
if (leftHeight > 0) {
PDF.addPage();
}
}
}
if (isDownload) {
PDF.save('仓库运服务质量报告' + '.pdf');
}
// 删除本地存储的base64字段
var pdfData = PDF.output('datauristring'); //获取base64Pdf
resolve(pdfData)
let shareContent = document.querySelector('#printer');
shareContent.style.height = '100vh';
pdfBox.style.display = 'block';
})
})
},
网友评论