使用插件html2canvas和jspdf插件
下载完两个插件后引入所需要的页面
import html2canvas from "html2canvas"
import jsPDF from "jspdf"
1、在导出之前将元素的高度或者宽度设置为滚动高度或者宽度,如:
el.style.height = el.scrollHeight + 'px';
2、转为图片之后再将高度/宽度设回来
el.style.height = el.clientHeight+ 'px'
以下导出pdf方法
export function exportPDF(titleName, id) {
document.body.scrollTop = document.documentElement.scrollTop = 0;
let el = document.querySelector("#my_table_1");
var clientH = el.clientHeight;
el.style.height = el.scrollHeight + 'px';
html2canvas(el, {
allowTaint: true,
useCORS: true,
dpi: 120,
background: "#142D42",
y: 0
}).then((canvas) => {
var currentPage = 1;
var leftHeight = canvas.height;
var a4Width = 576;
var a4Height = 772.89;
var a4HeightRef = Math.floor((canvas.width / a4Width) * a4Height);
var position = 0;
var pageData = canvas.toDataURL("image/jpeg", 1.0);
var pdf = new jsPDF("p", "pt", "a4");
pdf.addFont('simkai-normal.ttf', 'simkai', 'normal')
pdf.setFont('simkai')
pdf.setFontSize(20)
var index = 1,
canvas1 = document.createElement("canvas"),
height;
pdf.setDisplayMode("fullwidth", "continuous", "FullScreen");
function createImpl(canvas) {
if (leftHeight > 0) {
index++;
var checkCount = 0;
if (leftHeight > a4HeightRef) {
var i = position + a4HeightRef;
for (i = position + a4HeightRef; i >= position; i--) {
var isWrite = true;
for (var j = 0; j < canvas.width; j++) {
var c = canvas
.getContext("2d")
.getImageData(j, i, 1, 1).data;
if (c[0] != 0xff || c[1] != 0xff || c[2] != 0xff) {
isWrite = false;
break;
}
}
if (isWrite) {
checkCount++;
if (checkCount >= 10) {
break;
}
} else {
checkCount = 0;
}
}
height =
Math.round(i - position) || Math.min(leftHeight, a4HeightRef);
if (height <= 0) {
height = a4HeightRef;
}
} else {
height = leftHeight;
}
canvas1.width = canvas.width;
canvas1.height = height;
var ctx = canvas1.getContext("2d");
ctx.drawImage(
canvas,
0,
position,
canvas.width,
height,
0,
0,
canvas.width,
height
);
var pageHeight = Math.round((a4Width / canvas.width) * height);
if (position != 0) {
pdf.addPage();
}
pdf.addImage(
canvas1.toDataURL("image/jpeg", 1.0),
"JPEG",
10,
40,
a4Width,
(a4Width / canvas1.width) * height
);
leftHeight -= height;
position += height;
if (leftHeight > 0) {
setTimeout(createImpl, 500, canvas);
} else {
pdf.save(titleName + ".pdf");
el.style.height = clientH + 'px'
}
}
}
let targetPage = pdf.internal.getNumberOfPages();
if (leftHeight < a4HeightRef) {
pdf.addImage(
pageData,
"JPEG",
10,
40,
a4Width,
(a4Width / canvas.width) * leftHeight
);
pdf.save(titleName + ".pdf");
el.style.height = clientH + 'px'
} else {
try {
pdf.deletePage(0);
setTimeout(createImpl, 500, canvas);
} catch (err) {
}
}
})
}
vue页面使用
exportData(){
exportPDF("数据统计汇总",'my_table_1');
},